在使用节点网射的测试中模拟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();
});
});
});
编辑:
解决方案是将模拟的响应体传递给Web快照,而不是url:
webshot("<h1>Foo</h1>", ...发布于 2018-06-19 05:31:12
Nock期望http请求在相同的进程中发生。
注意:node-webshot是在另一个进程中运行的PhantonJS的包装器。
在您的示例中,Nock是在一个进程中设置的,但是http请求发生在另一个进程中。因此,您不能像您当前所做的那样模拟node-webshot所做的http请求。
您需要的是支持对内置在node-webshot中的http请求进行模拟。也就是说,如果没有这个特性,就必须将其添加到node-webshot中。
https://stackoverflow.com/questions/50920115
复制相似问题