[英]How to test an async function with callback in Jest?
I'm having a hard time finding info on how to test this function:我很难找到有关如何测试此 function 的信息:
const MyService = {
async stringify (entry, cb) {
try {
const response = await axios.post('localhost:3005/stringify', {
entry
})
cb(null, response.data)
} catch (minificationError) {
if (minificationError.response.status === 500) {
cb('error 1', null)
} else {
cb('error 2', null)
}
}
}
}
I understand I can import axios
and mock the .post
like this:我知道我可以导入axios
并像这样模拟.post
:
axios.post.mockResolvedValue({
data: { some: 'value' }
})
That'd work great if I the MyService was returning the promise... but how do I deal with the callback?如果我的 MyService 返回 promise,那会很好用……但是我该如何处理回调? Is this a bad practice and should the service be returning the promise and then handle errors in the component functions instead?这是一种不好的做法吗?服务应该返回 promise 然后处理组件函数中的错误吗?
Additionally, how would I mock a status code with jest (to test the failed states?)此外,我将如何开玩笑地模拟状态代码(以测试失败状态?)
First, you have to set up mock axios after that you have to call your mockapi's in your test case首先,你必须设置模拟axios然后你必须在你的测试用例中调用你的 mockapi
const axios = {
post: jest.fn(() => {
return Promise.resolve({
data: {},
});
}),
create: () => axios,
request: {},
defaults: {
adapter: {},
headers: {},
},
interceptors: {
request: {
use() {},
},
response: {
use() {},
},
},
};
Once you setup mock axios then you can access in your test case and return whatever mock response and status code you want.一旦你设置了模拟axios然后你就可以访问你的测试用例并返回你想要的任何模拟响应和状态代码。
mockAxios.post.mockImplementation((url) => {
if (url.includes("something")) {
return Promise.resolve({ data:{"response":""}, status: 200 });
}
return Promise.reject(new Error("not found"));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.