我如何使用 nock.js 来模拟 node-webshot 请求?
How can I use nock.js to mock node-webshot requests?
模拟 node Webshot during a test using 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 Webshot during a test using 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
中。