14

我想测试我的 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();
    });
  });
});

但我在这里得到错误

错误:在 TCPConnectWrap.afterConnect [as oncomplete] (net.js:1158:14) 处连接 ECONNREFUSED 127.0.0.1:80

如果我用 axios 替换 api.js axios.create() 它的工作。但是如何使用创建的 axios 实例进行测试?我需要在创建它时设置参数。

任何人都可以帮忙吗?

4

1 回答 1

27

嗨,我有同样的问题,不得不在这里回答自己https://stackoverflow.com/a/51414152/73323

这是要点:

首先,您不需要axios-mock-adapter图书馆。

axios为in创建一个模拟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)
})
于 2018-07-19T04:08:07.693 回答