Mock-axios-адаптер не дразнит получить запрос - PullRequest
0 голосов
/ 11 декабря 2018

Я пытаюсь проверить эту функцию:

export const fetchCountry = (query) => {
  return dispatch => {
    dispatch(fetchCountryPending());
    return axios.get(`${process.env.REACT_APP_API_URL}/api/v1/countries/?search=${query}`)
      .then(response => {
        const country = response.data;
        dispatch(fetchCountryFulfilled(country));
      })
      .catch(err => {
        dispatch(fetchCountryRejected());
        dispatch({type: "ADD_ERROR", error: err});
      })
  }
}

Вот мой тест:

describe('country async actions', () => {
  let store;
  let mock;

  beforeEach(() => {
    mock = new MockAdapter(axios)
    store = mockStore({ country: [], fetching: false, fetched: false })
  });

  afterEach(() => {
    mock.restore();
    store.clearActions();
  });

  it('dispatches FETCH_COUNTRY_FULFILLED after axios request', () => {
    const query = 'Aland'
    mock.onGet(`/api/v1/countries/?search=${query}`).reply(200, country)
    store.dispatch(countryActions.fetchCountry(query))
      .then(() => {
        const actions = store.getActions();
        expect(actions[0]).toEqual(countryActions.fetchCountryPending())
        expect(actions[1]).toEqual(countryActions.fetchCountryFulfilled(country))
      });
  });

Когда я запускаю этот тест, я получаю сообщение об ошибке UnhandledPromiseRejectionWarning и что fetchCountryPending былне получено и что fetchCountryRejected было.Кажется, что onGet () ничего не делает.Когда я комментирую строку mock.onGet('/api/v1/countries/?search=${query}').reply(200, country), я получаю точно такой же результат, заставляя меня поверить, что ничего не высмеивают.Что я делаю не так?

1 Ответ

0 голосов
/ 28 марта 2019

Я не смог заставить .then (() => {}) работать, поэтому я превратил функцию в асинхронную функцию и ждал отправки:

  it('dispatches FETCH_COUNTRY_FULFILLED after axios request', async () => {
    const query = 'Aland'
    mock.onGet(`/api/v1/countries/?search=${query}`).reply(200, country)
    await store.dispatch(countryActions.fetchCountry(query))
    const actions = store.getActions();
    expect(actions[0]).toEqual(countryActions.fetchCountryPending())
    expect(actions[1]).toEqual(countryActions.fetchCountryFulfilled(country))
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...