node.js - 如何使用 nock.js 模拟 Node-Webshot 请求?

标签 node.js mocha.js nock

模拟 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/

相关文章:

node.js - 如何在除 Nodejs 之外的任何应用程序中使用 POE 的 API?

javascript - 来自 Node JS 的用户定义的 javascript 函数

node.js - 用 mocha 和 chai 测试 node.js

node.js - Nock 未在 Redux 测试中拦截 API 调用

reactjs - 集成测试 - redux/react + nock.js

javascript - 测试异步 async await JavaScript 函数

javascript - nodejs 中的 RTMP 实现是可能的吗?

node.js - 如何限制 Node 进程的 CPU 和内存使用率

javascript - 在 mocha 测试中使用 es6

node.js - 如何使用 supertest 和 mocha 测试快速渲染