首页 > 解决方案 > 如何使用提供的操作通过模拟 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);

    });
  });

提前致谢。

标签: reactjstestingmockingjestjsaxios

解决方案


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

推荐阅读