reactjs - 如何使用提供的操作通过模拟 Axios 编写一个 Jest 测试?

标签 reactjs testing mocking jestjs axios

我是使用 jest 进行测试的新手,我一直在研究如何测试给出的这段代码,以显示在调用 registerUser 时调用了 Axios.post。我在网上搜索过,没有可靠的解决方案可以发布。如能提供解决方案,将不胜感激

这是我需要从 authAction.js 测试的功能

export const registerUser = (userData, history) => dispatch => {
  axios
    .post("/api/users/register", userData)
    .then(res => history.push("/login")) // re-direct to login on successful register
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

我已经试过了,但似乎不起作用。

import * as authActions from './authActions';
import axios from 'axios';
import configureStore from 'redux-mock-store'; //ES6 modules
import thunk from 'redux-thunk';
const middleware = [thunk];
const mockStore = configureStore(middleware);


describe('test register user axios', () => {
    it('should give a response of 201 back after it registers user', () => {


        var userData = {email: "kamara@fc.come",
        name: "Kris Kamara",
        password: "adam123",
        password2: "adam123"
        }

        var history = jest.fn();

        const initialState = {}
        const store = mockStore(initialState)

        store.dispatch(authActions.registerUser({userData}, history));
        expect(axios).toHaveBeenCalledTimes(1);

    });
  });

提前致谢。

最佳答案

像这样从函数中返回 Promise:

export const registerUser = (userData, history) => dispatch => {
  return axios  // <= return the Promise
    .post("/api/users/register", userData)
    .then(res => history.push("/login")) // re-direct to login on successful register
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

...然后你可以这样测试它:

import * as authActions from './authActions';
import axios from 'axios';

describe('registerUser', () => {

  let mock;
  beforeEach(() => {
    mock = jest.spyOn(axios, 'post');
  });
  afterEach(() => {
    mock.mockRestore();
  });

  it('should register the user and redirect to login', async () => {
    const push = jest.fn();
    const history = { push };
    const dispatch = jest.fn();
    mock.mockResolvedValue();  // mock axios.post to resolve

    await authActions.registerUser('the user data', history)(dispatch);

    expect(mock).toHaveBeenCalledWith('/api/users/register', 'the user data');  // Success!
    expect(history.push).toHaveBeenCalledWith('/login');  // Success!
  });
});

关于reactjs - 如何使用提供的操作通过模拟 Axios 编写一个 Jest 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55455351/

相关文章:

reactjs - es6 React在子组件中获取 Prop

javascript - Touchableopacity onpress 在 SVG 标签内不起作用

C# REPL 工具;类似控制台的快速编译工具

ruby-on-rails - Rails 测试失败

mocking - 在 XCTest 中快速模拟对象的最佳方法是什么?

python - 如何模拟类并使用 pytest-mock 控制 py.test 中的返回值?

javascript - 无法卸载 React 组件,从父组件返回 false

reactjs - Apollo Client + Server 如何处理同一查询中重复的相关节点?

testing - JMeter- 从 CLI 运行时不会替换属性值

c# - 没有可用的匹配绑定(bind),并且该类型不可自绑定(bind)。激活 IProductsRepository 时出错