reactjs - 我想用 moxios 测试反应 API
问题描述
我正在学习用笑话和酶进行测试。我想用 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]
}
}))
})}, [])
我想用 moxios 测试一下。我已经这样做了:
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();
});
});
});
推荐阅读
- flutter - 如何修复错误状态:DocumentSnapshotPlatform 中不存在字段
- google-sheets - 如何在谷歌表格中以文本格式计算数字
- azure - 未能向托管实例授予“读取”权限
- json - 我正在努力处理未处理的异常:类型'_InternalLinkedHashMap
'不是颤振中类型转换中的'String'类型的子类型 - apache-kafka - 如何知道kafka生产者IP地址?
- neural-network - 如何调模型?
- opengl - 对纹理采样器的纹理单元值感到困惑
- git-extensions - Git 扩展 - 功能区中的自定义按钮
- shell - ADB 命令自动化
- linux - 将脚本输出保存到文件时出现问题