Roh*_*aul 5 node.js express reactjs nock
这是在后端和前端运行良好的 Express Route 代码。
// 按 Vessel_type by_id 编辑/更新 - 工作
router.put("/:id", (req, res, next) => {
Vessel_Type.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true },
(err, updatedRecord) => {
if (err) {
console.error(err);
return next(err);
} else {
res.status(200).send(updatedRecord);
}
}
);
});
Run Code Online (Sandbox Code Playgroud)
这是我在 React 前端使用nock进行 API 测试的代码
it("API test-3 - PUT (/api/vesseltype/id)", done => {
nock(host)
.defaultReplyHeaders({
"access-control-allow-origin": "*",
"Content-Type": "application/json"
})
.persist()
.log(console.log)
.put("/api/vesseltype/5c62cc8f1774b626cd7fdbe6", {
vesseltype: "Super Large Cargo Ship-45"
})
.delayBody(1000)
.reply(200, "PUT/EDIT data with reqheaders");
axios
.put("http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6", {
vesseltype: "Super Large Cargo Ship-45"
})
.then(response => {
expect(response.data).toBe("PUT/EDIT data with reqheaders");
expect(typeof response.data).toBe("string");
done();
});
});
Run Code Online (Sandbox Code Playgroud)
测试错误的控制台记录在终端中给出以下内容
console.log node_modules/nock/lib/interceptor.js:332
matching http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6 to PUT http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6: false
console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: Nock: No match for request {
"method": "OPTIONS",
"url": "http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6",
"headers": {
"origin": "http://localhost",
"access-control-request-method": "PUT",
"user-agent": "Mozilla/5.0 (linux) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/11.12.0",
"host": "localhost:3000",
"content-length": 0
}
}
at Object.dispatchError (/home/paul/codes-Lap/React/Volteo/IES/IES-Rohan-WIP/client/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at EventEmitter.client.on.err (/home/paul/codes-Lap/React/Volteo/IES/IES-Rohan-WIP/client/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
at EventEmitter.emit (events.js:202:15)
Run Code Online (Sandbox Code Playgroud)
然而,我的 PUT 路由(http://localhost:3000/api/vesseltype/5c62cc8f1774b626cd7fdbe6)在 nock 和 axios 之间完美匹配。
| 归档时间: |
|
| 查看次数: |
2609 次 |
| 最近记录: |