javascript - 如何使用Jest和Axios进行功能覆盖?

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

最佳答案

这是一个工作示例:

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/

相关文章:

c# - TDD 与 DDD MVC

javascript - 如何在解构赋值语法中使用特殊字符(如连字符)?

reactjs - store.dispatch、useDispatch和useReducer的dispatch有什么区别?

javascript - 如何读取图像 blob url 或将其转换为图像?

typescript - 类型检查 createAction Redux 助手

unit-testing - 如何构建 Haskell 项目?

javascript - 使用 qUnit 时如何在每次测试前运行一个函数?

javascript - 开发 JavaScript 库时应该使用命名函数吗?

javascript - 如何知道用户是否输入了无效的$routeparams

javascript - 如何通过 Javascript 注入(inject)访问 Angular 属性