繁体   English   中英

模拟-axios-适配器不模拟获取请求

[英]Mock-axios-adapter not mocking get request

我正在尝试测试此功能:

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) ,最终得到的结果完全相同,使我相信没有任何结果被嘲笑。 我究竟做错了什么?

我无法使.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))
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM