【问题标题】:Write test axios-mock-adapter with axios.create()使用 axios.create() 编写测试 axios-mock-adapter
【发布时间】:2018-12-18 02:18:11
【问题描述】:

我想测试我的 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 [as oncomplete] (net.js:1158:14)

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

有人可以帮忙吗?

【问题讨论】:

    标签: axios jestjs axios-mock-adapter


    【解决方案1】:

    您好,我遇到了同样的问题,不得不在这里回答自己https://stackoverflow.com/a/51414152/73323

    这里是要点:

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

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

    // 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)
    })
    

    【讨论】:

    • 我必须像 const mockAxios = jest.genMockFromModule<AxiosStatic>('axios') 那样强烈键入 mockAxios,并使用 ts-jest/utils 中的模拟函数包装 mockAxios。我的实现最终是这样的:mocked(mockAxios.post).mockImplementationOnce(() => Promise.resolve({ data: task }), )
    猜你喜欢
    • 2018-06-13
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多