我正在学习用jest和酶进行测试。我想用moxios测试API,但面临很多挑战。我有一个API调用如下:
useEffect(() => {axios.get(`https://API/call/with/dynamicvalue/${id}`,
{
headers: {
Authorization: `Basic ${btoa(getToken())}`,
},
}).then((response)=>{
let MoreData=response.data;
console.log(MoreData)
setFullAuditDetails(MoreData.data.slice(0,20).map(d=>{
return{
timeF: d.time.split('T')[0],
actionF: d.method,
userF: d.userName.split('.')[0]
}
}))
})}, [])
我想用莫西奥斯测试一下。我已经做到了:
const api = `https://API/call/with/dynamicvalue/372c7861-e09a-41ae-8c6d-7bbc7877ad79`
describe("Tests for API", () => {
beforeEach(() => {
moxios.install()
})
afterEach(() => {
moxios.uninstall()
})
test("Check for the response", (done) => {
moxios.wait(() => {
const request = moxios.stubRequest(api)
request.respondWith({ status: 200,
response: { "success": true }
}) //mocked response
.then(response => {
console.log(response);
expect('status').toEqual('200');
done();
wrapper2.unmount();
})
})
});
})
获取错误:
TypeError: Cannot read property 'respondWith' of undefined
37 | moxios.wait(() => {
38 | const request = moxios.stubRequest(api)
> 39 | request.respondWith({ status: 200,
| ^
40 | response: { "success": true }
41 | }) //mocked response
42 | .then(response => {
但不知道该怎么做。任何帮助都将不胜感激。
终于找到了一个解决方案:
describe("Tests for API", () => {
beforeEach(() => {
moxios.install()
})
afterEach(() => {
moxios.uninstall()
})
test("Check for the response", (done) => {
// moxios.wait(() => {
moxios.stubRequest(api, { status: 200,
response: { "success": true }
}) //mocked response
axios.get(api, { "success": true }).then(response => {
// console.log(response);
expect(response.status).toBe(200);
done();
});
});
});