在React中使用Jest模拟Axios-未调用模拟功能

时间:2019-02-28 17:14:39

标签: reactjs jestjs

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

这是我的/__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));
  });

但是由于某些原因,我继续收到错误消息:

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

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

2 个答案:

答案 0 :(得分:0)

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

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

因此,要使其正常工作,我不得不使用redux-mock-store npm模块来模拟商店。新的测试代码如下:

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

现在可以通过测试。

答案 1 :(得分:-1)

我认为您没有正确设置模拟。

mockAxios.post.mockImplementationOnce

应更改为

mockAxios.post = jest.fn().mockResolvedValueOnce('bloofblurg');

然后,您可以再次检查一次post是否已被调用并解析了期望值。

expect(mockAxios.post).resolves.toBe('bloofblurg');

请参见

  1. https://jestjs.io/docs/en/mock-function-api#mockfnmockresolvedvalueoncevalue
  2. https://jestjs.io/docs/en/expect#resolves