我正在使用nock
来拦截fetch
对https://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.com
,nock
告诉我它没有捕获到获取请求。但是,如果我关闭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请求
我找到了答案。我的代码我正在调用nock.restore();
,我的代码是异步的。我猜我在其他测试运行时正在恢复nock模拟。然而,删除nock.restore();
做了伎俩,因为nock总是拦截一个电话只有它没关系。