nock处理fetch req但不阻止http调用

问题描述 投票:0回答:1

我正在使用nock来拦截fetchhttps://www.youtube.com/oembed?url=https://youtu.be/m4hklkGvTGQ的召唤。像这样:

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)我的测试表现/失败,如预期
  • 如果我将拦截网址从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 jest nock
1个回答
0
投票

我找到了答案。我的代码我正在调用nock.restore();,我的代码是异步的。我猜我在其他测试运行时正在恢复nock模拟。然而,删除nock.restore();做了伎俩,因为nock总是拦截一个电话只有它没关系。

© www.soinside.com 2019 - 2024. All rights reserved.