gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:15:18 25 4
gpt4 key购买 nike

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

但是我在这里出错

Error: connect ECONNREFUSED 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1158:14)



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

有人可以帮忙吗?

最佳答案

嗨,我遇到了同样的问题,不得不在这里回答自己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)
})

关于axios - 使用axios.create()编写测试axios-mock-adapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51261781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com