模拟 node Webshot 发送的请求的正确方法是什么?在使用nock.js进行测试期间?
我尝试使用以下代码来捕获 http://example.com/foo.html 的模拟响应作为 foo.png
但模拟似乎不起作用。
const nock = require("nock");
const webshot = require("webshot");
describe("mock webshot request", function(){
this.timeout(20000);
beforeEach(function(){
nock("http://example.com").persist().get("/foo.html").reply(200, "<h1>Foo</h1>");
});
afterEach(function () {
nock.cleanAll();
});
it("captures mocked response", function(done){
webshot("http://example.com/foo.html", "foo.png",function(err) {
nock.isDone();
if(!err) done();
});
});
});
编辑:
解决方案是将模拟的响应正文传递给 Webshot 而不是 url:
webshot("<h1>Foo</h1>", ...
最佳答案
Nock
期望 http 请求发生在同一进程中。
注意: node-webshot
是在另一个进程中运行的 PhantonJS 的包装器。
在您的情况下,Nock
是在一个进程中设置的,但 http 请求发生在另一进程中。因此,您无法像您当前所做的那样模拟由 node-webshot
完成的 http 请求。
您需要的是对内置于 node-webshot
中的模拟 http 请求的支持,即,如果 node-webshot
没有此功能,则必须将此功能添加到 node-webshot
中。
关于node.js - 如何使用 nock.js 模拟 Node-Webshot 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920115/