使用axios.create()编写测试axios-mock-adapter

时间:2018-07-10 09:32:08

标签: axios jestjs axios-mock-adapter

我想测试我的http服务,但出现错误。 所以,我的测试文件

api.js

import axios from 'axios';

export const api = axios.create();

fetchUsers.js

import api from './api';
export const fetchUsers = (params) api.get('/api/users', { params })
  .then(({data}) => data)

fetchUsers.spec.js

import MockAdapter from 'axios-mock-adapter'
import api from './api';
const mock = new MockAdapter(api);

describe('fetchUsers', () => {
  it('should send request', (done) => {
    const data = { data: ['user'] };
    mock.onGet('/api/users').reply(200, data);

    fetchUsers().then((response) => {
      expect(response).toEqual(data.data);
      done();
    });
  });
});

但是我在这里出错

  

错误:连接ECONNREFUSED 127.0.0.1:80       在TCPConnectWrap.afterConnect上[完整完成](net.js:1158:14)

如果我将api.js中的axios.create()替换为axios,则其正常工作。但是如何测试创建的axios实例呢?创建它时,我需要在其中添加参数。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:6)

嗨,我遇到了同样的问题,不得不在这里https://stackoverflow.com/a/51414152/73323

回答自己。

要点在这里:

首先,您不需要axios-mock-adapter库。

axios中为src/__mocks__创建一个模拟:

// src/__mocks__/axios.ts

const mockAxios = jest.genMockFromModule('axios')

// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)

export default mockAxios

然后在您的测试文件中,要旨如下:

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

// for some reason i need this to fix reducer keys undefined errors..
jest.mock('../../store/rootStore.ts')

// you need the 'async'!
test('Retrieve transaction data based on a date range', async () => {
  const middlewares = [thunk]
  const mockStore = configureMockStore(middlewares)
  const store = mockStore()

  const mockData = {
    'data': 123
  }

  /** 
   *  SETUP
   *  This is where you override the 'post' method of your mocked axios and return
   *  mocked data in an appropriate data structure-- {data: YOUR_DATA} -- which
   *  mirrors the actual API call, in this case, the 'reportGet'
   */
  mockAxios.post.mockImplementationOnce(() =>
    Promise.resolve({ data: mockData }),
  )

  const expectedActions = [
    { type: REQUEST_TRANSACTION_DATA },
    { type: RECEIVE_TRANSACTION_DATA, data: mockData },
  ]

  // work
  await store.dispatch(reportGet())

  // assertions / expects
  expect(store.getActions()).toEqual(expectedActions)
  expect(mockAxios.post).toHaveBeenCalledTimes(1)
})