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

问题描述 投票:1回答:1

如何使用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个回答
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
});
© www.soinside.com 2019 - 2024. All rights reserved.