本文介绍了在React中用Jest模拟Axios-未调用模拟功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Jest进行单元测试.测试的一部分是模拟Axios,但是由于某种原因,它没有被调用.

I am trying to use Jest for unit testing. Part of the testing is to mock Axios, but for some reason it is not being called.

这是我的/__mocks__/axios.js代码:

export default {
  post: jest.fn(() => Promise.resolve({})),
};

这是我的测试代码:

import mockAxios from 'axios';
import { registerUser } from '../../actions/auth';
import user from '../fixtures/user';


describe('Register User', () => {
  test('Should call register API and redirect to login', async () => {
    const historyMock = { push: jest.fn() };

    mockAxios.post.mockImplementationOnce(() => Promise.resolve());

    await registerUser(user, historyMock);

    expect(mockAxios.post).toHaveBeenCalledTimes(1);

  });
});

这也是注册用户代码:

export const registerUser = (user, history) => dispatch => axios
  .post('/users/register', user)
  .then(() => history.push('/login'))
  .catch((err) => {
    dispatch(handleError(err));
  });

但是由于某些原因,我仍然会收到错误消息:

But for some reason I continue to get the error:

Register User › Should call register API and redirect to login

    expect(jest.fn()).toHaveBeenCalledTimes(1)

    Expected mock function to have been called one time, but it was called zero times.

      35 |     await registerUser(user, historyMock);
      36 |
    > 37 |     expect(mockAxios.post).toHaveBeenCalledTimes(1);

有什么想法为什么模拟不起作用?

Any ideas why the mock is not working?

推荐答案

正如@jonrsharpe在评论中指出的那样,registerUser函数正在返回该函数:

As @jonrsharpe pointed out in the comments, the registerUser function was returning the function:

dispatch => axios
  .post('/users/register', user)
  .then(() => history.push('/login'))
  .catch((err) => {
    dispatch(handleError(err));
  });

因此,为了使其正常工作,我不得不使用 redux-mock-store npm模块.新的测试代码如下:

So in order for this to work, I had to had to mock the store using the redux-mock-store npm module. The new test code looks like:

import mockAxios from 'axios';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';

import { setCurrentUser, registerUser } from '../../actions/auth';
import user from '../fixtures/user';

const defaultStoreState = { errors: {}, auth: { isAuthenticated: false, user: {} } };
const createMockStore = configureMockStore([thunk]);

describe('Register User', () => {
  test('Should call register API and redirect to login', (done) => {
    const mockStore = createMockStore(defaultStoreState);
    const historyMock = { push: jest.fn() };

    mockStore.dispatch(registerUser(user, historyMock)).then(() => {
      expect(mockAxios.post).toHaveBeenCalledTimes(1);
      expect(historyMock.push).toHaveBeenCalledTimes(1);
      expect(historyMock.push).toHaveBeenCalledWith('/login');

      done();
    });
  });
});

现在可以通过测试.

这篇关于在React中用Jest模拟Axios-未调用模拟功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:01