这是在后面和前端正常工作的快速路由代码。
//vessel_type by_id edit/eford/更新 - 工作
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);
}
}
);
});
这是我的API测试代码,在nock
的前端中 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();
});
});
测试中误差的控制台记录在终端中给出以下内容
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)
但是,我的put路线(http://localhost:3000/api/api/wesselType/5c62cc8f1774b626cd7fdbe6)在nock和axios之间都匹配。
我经历了这些github问题,在这里,这里和这里问题,但是这些解决方案对我没有帮助。
如果您使用的是jest react,则开玩笑的配置将 testEnviromnent
设置为 jsdom
。但是Nock需要一个node
环境才能模拟Axios。
一个解决方法是在Nock测试中设置Jest testenvironment仅文件,以免干扰您的React测试。您可以通过在测试网络呼叫的Jest Files的顶部添加此DocBlock来做到这一点:
/** @jest-environment node */
显然是在调用put之前的框架/lib调用选项请求。它与CORS有关。此处描述
您可以尝试nock-ing选项。