Axios模拟请求问题



我有这个Axios请求,需要使用jest进行覆盖,但是我不能。

jest版本:27.2.5
axios版本:0.25.0
nestJS版本:8.2.5

index.js

await axios
.get('url_here', {
headers: {
'user-id': userId,
},
})
.then(function (res) {
return res.data;
})
.catch(function (err) {
throw new NotFoundException(err.response.data);
});

index.spec.js

describe('When to call group service', () => {
let service: TestService;
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
...
});

最后我找到了一个解决方案,使用这篇文章的一部分:

https://www.csrhymes.com/2022/03/09/mocking-axios-with-jest-and-typescript.html

第一步:需要使用jest.mock('axios'),而不是测试文件开头所描述的。

第二步:在测试文件
const mockedAxios = axios jest.MockedFunction<typeof axios>

中,有必要使用这个带有typeof的模拟函数来正确地工作

第三步:现在需要按照这个属性模型创建一个模拟请求响应来工作!

const resp = {
data: [{ id: 1, nickname: 'teste' }],
status: 200,
statusText: 'Ok',
headers: {},
config: {},
};

第四步:在测试文件

中定义模拟
的响应
mockedAxios.mockResolvedValueOnce(resp);

,最后,需要重构初始axios请求:
索引文件

await axios('url_here', {
method: 'GET'
headers: {
'user-id': userId,
},
})
.then(function (res) {
return res.data;
})
.catch(function (err) {
throw new NotFoundException(err.response.data);
});

改变调用函数。get使用方法的静态定义作为属性,因为在我收到错误之前,它没有定义

为我的错误感到抱歉,因为这是我第一次在stackoverflow中写东西。

最新更新