简体   繁体   English

如何模拟 axios 类

[英]How to mock an axios class

I am writing tests for my asynchronous actions.我正在为我的异步操作编写测试。 I have abstracted away my axios calls into a separate class.我已经将 axios 调用抽象到一个单独的类中。 If I want to test my asynchronous redux action, how do I write a mock for api.js so that sampleAction.test.js will pass?如果我想测试我的异步 redux 操作,我如何为api.js编写模拟以便sampleAction.test.js能够通过? Thanks!谢谢!

api.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: import Api from './api'; 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: 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);
  });
});

You can mock Api.get like this:你可以像这样模拟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!
});

...or you can mock api.js like this: ...或者你可以像这样模拟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!
});

...or you can auto-mock api.js and fill in the return value for Api.get : ...或者你可以自动模拟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!
});

...or you can create a manual mock at ./__mocks__/api.js : ...或者你可以在./__mocks__/api.js创建一个手动模拟

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

...and activate it in your test like this: ...并在您的测试中激活它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM