如何使用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));
}
}
最佳答案
这是一个工作示例:
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
});
关于javascript - 如何使用Jest和Axios覆盖功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54729667/