如何使用Jest和Axios覆盖功能?

时间:2019-02-17 02:43:00

标签: javascript redux tdd jestjs axios

如何使用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));
    }
}

1 个答案:

答案 0 :(得分:0)

这是一个有效的示例:

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
});