【问题标题】:nock handles fetch req but does not prevent http callnock 处理 fetch req 但不阻止 http 调用
【发布时间】:2017-12-23 14:31:18
【问题描述】:

我正在使用 nock 拦截对 https://www.youtube.com/oembed?url=https://youtu.be/m4hklkGvTGQfetch 调用。像这样:

it(`properly responds to YouTube URL ${url}`, async () => {
    nock('https://www.youtube.com')
        .get('/oembed')
        .query(true)
        .reply(200, remoteResponse);
    const youTube = new YouTube(url);
    const response = await youTube.getResponse(); // this contains the fetch call
    expect(response).toEqual(expectedResponse);
    nock.restore();
});

我看到nock 正确拦截了我的fetch,因为

  • 如果我更改 remoteResponse(参见 5.reply(200, remoteResponse) 行,我的测试会按预期运行/失败
  • 如果我将拦截 url 从 https://www.youtube.com 更改为 https://www.sometingelse.comnock 会告诉我它没有捕获到获取请求。

但是,如果我关闭 WiFi 并运行测试,我可以看到我的应用程序会警告我 HTTP 请求失败:

https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=m4hklkGvTGQ 的请求失败,原因:getaddrinfo ENOTFOUND www.youtube.com www.youtube.com:443

另外,当我运行我的测试时,它们大约需要 1 秒(这似乎已经很长了),当我打开我的 WiFi 时,它们会立即完成。

不知道为什么还有http请求

【问题讨论】:

    标签: javascript testing fetch jestjs nock


    【解决方案1】:

    我找到了答案。我正在调用nock.restore(); 的代码,而我的代码是异步的。我猜我在运行其他测试时正在恢复 nock 模拟。但是,删除 nock.restore(); 就可以了,因为 nock 总是拦截单个调用,所以没问题。

    【讨论】:

      猜你喜欢
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2012-03-21
      • 1970-01-01
      • 2021-03-25
      • 2011-04-24
      相关资源
      最近更新 更多