如何使用提供的动作通过模拟Axios编写笑话测试?

Aar*_*ath 2 testing mocking reactjs jestjs axios

我是使用玩笑进行测试的新手,但我坚持如何测试这段代码,以表明在调用我的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
      })
    );
};
Run Code Online (Sandbox Code Playgroud)

我已经尝试过了,但是似乎没有用。

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

    });
  });
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Bri*_*ams 5

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
      })
    );
};
Run Code Online (Sandbox Code Playgroud)

...然后您可以像这样测试它:

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!
  });
});
Run Code Online (Sandbox Code Playgroud)