如何模拟axios类

问题描述 投票:1回答:1

我正在为我的异步操作编写测试。我把我的axios调用抽象成一个单独的类。如果我想测试我的异步redux动作,我如何为api.js编写一个模拟,以便sampleAction.test.js通过?谢谢!

api.js:

import axios from 'axios';

let apiUrl = '/api/';
if (process.env.NODE_ENV === 'test') {
  apiUrl = 'http://localhost:8080/api/';
}

export default class Api {
  static async get(url) {
    const response = await axios.get(`${apiUrl}${url}`, {withCredentials: true});
    return response;
  }
}

sampleAction.js:从'./api'导入Api;

export const fetchData = () => async (dispatch) => {
  try {
    const response = await Api.get('foo');
    dispatch({
      type: 'RECEIVE_DATA',
      data: response.data.data,
    });
  } catch (error) {
    handleError(error);
  }
};

sampleAction.test.js:

import store from './store';

test('testing RECEIVE_DATA async action', () => {
  const expectedActions = [
    { type: 'RECEIVE_DATA', data: 'payload' },
  ];
  return store.dispatch(actions.fetchData()).then(() => {
    expect(store.getActions()).toEqual(expectedActions);
  });
});
javascript redux jestjs axios moxios
1个回答
1
投票

你可以像这样模仿Api.get

import { fetchData } from './sampleAction';
import Api from './api';

let getMock;
beforeEach(() => {
  getMock = jest.spyOn(Api, 'get');
  getMock.mockResolvedValue({ data: { data: 'mock data' } });
});
afterEach(() => {
  getMock.mockRestore();
});

test('testing RECEIVE_DATA async action', async () => {
  const dispatch = jest.fn();
  await fetchData()(dispatch);
  expect(getMock).toHaveBeenCalledWith('foo');  // Success!
  expect(dispatch).toHaveBeenCalledWith({
    type: 'RECEIVE_DATA',
    data: 'mock data'
  });  // Success!
});

...或者你可以像这样嘲笑api.js

import { fetchData } from './sampleAction';
import Api from './api';

jest.mock('./api', () => ({
  get: jest.fn(() => Promise.resolve({ data: { data: 'mock data' } }))
}));

test('testing RECEIVE_DATA async action', async () => {
  const dispatch = jest.fn();
  await fetchData()(dispatch);
  expect(Api.get).toHaveBeenCalledWith('foo');  // Success!
  expect(dispatch).toHaveBeenCalledWith({
    type: 'RECEIVE_DATA',
    data: 'mock data'
  });  // Success!
});

...或者您可以自动模拟api.js并填写Api.get的返回值:

import { fetchData } from './sampleAction';
import Api from './api';

jest.mock('./api');  // <= auto-mock
Api.get.mockResolvedValue({ data: { data: 'mock data' } });

test('testing RECEIVE_DATA async action', async () => {
  const dispatch = jest.fn();
  await fetchData()(dispatch);
  expect(Api.get).toHaveBeenCalledWith('foo');  // Success!
  expect(dispatch).toHaveBeenCalledWith({
    type: 'RECEIVE_DATA',
    data: 'mock data'
  });  // Success!
});

...或者你可以在manual mock创建一个./__mocks__/api.js

export default {
  get: jest.fn(() => Promise.resolve({ data: { data: 'mock data' } }))
}

...并在你的测试中激活它,如下所示:

import { fetchData } from './sampleAction';
import Api from './api';

jest.mock('./api');  // <= activate manual mock

test('testing RECEIVE_DATA async action', async () => {
  const dispatch = jest.fn();
  await fetchData()(dispatch);
  expect(Api.get).toHaveBeenCalledWith('foo');  // Success!
  expect(dispatch).toHaveBeenCalledWith({
    type: 'RECEIVE_DATA',
    data: 'mock data'
  });  // Success!
});
© www.soinside.com 2019 - 2024. All rights reserved.