【问题标题】:How to cover function using Jest and Axios?如何使用 Jest 和 Axios 覆盖功能?
【发布时间】:2019-02-17 02:42:59
【问题描述】:

如何使用 Jest 和 Axios 覆盖 searchLocation()?

export const searchLocation = () => {
    return dispatch => {
        dispatch(searchLocationStart());
        axios.get("https://api.github.com/users/octocat")
            .then((data) => dispatch(searchLocationSuccess(data.data)))
            .catch(() => dispatch(searchLocationError));
    }
}

【问题讨论】:

    标签: javascript redux tdd jestjs axios


    【解决方案1】:

    这是一个工作示例:

    import * as axios from 'axios';
    
    // stubs for the example
    const searchLocationStart = () => ({ type: 'start' });
    const searchLocationSuccess = (data) => ({ type: 'success', payload: data });
    
    const searchLocation = () => {
      return dispatch => {
          dispatch(searchLocationStart());
          return axios.get("https://api.github.com/users/octocat")  // return the Promise
              .then((data) => dispatch(searchLocationSuccess(data.data)))
              .catch(() => dispatch(searchLocationError));
      }
    }
    
    test('searchLocation', async () => {  // use an async test function
      const spy = jest.spyOn(axios, 'get');  // mock axios.get (this is one way to do it)
      spy.mockImplementation(() => Promise.resolve({ data: 'the result' }));
    
      const result = searchLocation();
      const dispatch = jest.fn();  // use a mock function for dispatch
      await result(dispatch);  // await the returned Promise
    
      // check that dispatch was called with the correct actions
      expect(dispatch.mock.calls[0]).toEqual([{type: "start"}]);  // SUCCESS
      expect(dispatch.mock.calls[1]).toEqual([{type: "success", payload: 'the result'}]);  // SUCCESS
    });
    

    【讨论】:

    • 测试错误情况类似,模拟 axios.get 以返回 Promise.reject 并检查 dispatch 是否使用来自 searchLocationError 的操作调用。
    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2018-05-03
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多