【问题标题】:How can I use nock.js to mock node-webshot requests?如何使用 nock.js 模拟 node-webshot 请求?
【发布时间】:2018-06-19 03:14:05
【问题描述】:

在使用nock.js 的测试期间模拟node Webshot 发送的请求的正确方法是什么?

我尝试使用以下代码将 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>", ...

【问题讨论】:

  • 你在嘲笑foo.html,但在测试foor.html
  • 感谢您指出错字。问题现已编辑。

标签: node.js mocha.js nock


【解决方案1】:

Nock 期望 http 请求发生在同一个进程中。

注意:node-webshot 是 PhantonJS 的包装器,它在另一个进程中运行。

在您的情况下,Nock 是在一个进程中设置的,但 http 请求发生在另一个进程中。所以你不能像你目前正在做的那样模拟node-webshot完成的http请求。

您需要的是支持 node-webshot 中内置的模拟 http 请求,即,如果 node-webshot 没有此功能,则必须将此功能添加到它。

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 2017-10-01
    • 2018-08-26
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2016-11-27
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多