立即禁用单个nock范围以重新设置模拟URL

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

使用nock,有没有办法禁用单个Nock范围?我一直在努力进行一些测试,这些测试设置了与其他测试相同的URL标记。它们都可以单独正常运行,但是当在同一个Mocha会话中运行时,它们之一会失败,因为我无法重新对活动的Nock范围进行nock,这意味着设置的Nocks可以捕获所有请求。

我尝试过的:

  • 如果我在before()中设置了一些Nocks,然后在我的scope.persist(false)中调用了after(),则它只会“取消持久化”作用域,因此它对于一个更多请求是有效的。它不会立即禁用它。
  • [我发现nock.cleanAll()立即禁用了Nocks,以便可以再次设置它们,但是随后,它[[也禁用了可能已经设置过的所有全局Nocks,对于所有测试用例都是如此。] >
  • 到目前为止,我发现的唯一解决方案是1)对所有nocks使用唯一的URL:s,这并不总是可能的;或者2)使用nock.cleanAll()并且不依赖于任何全局nocks-而是确保仅在本地before()功能中设置Nocks,包括为需要它们的每个测试重复设置全局Nocks。

似乎能够做到的非常有用

scope = nock('http://somewhere.com').persist().get('/'.reply(200, 'foo');

然后在一系列测试中使用该小头,最后执行

scope.remove();

但是,我无法执行这样的操作。有可能吗?

示例:

before(async () => { nock('http://common').persist().get('/').reply(200, 'common'); }); after(async () => { }); describe('Foo tests', () => { let scope; before(async () => { scope = nock('http://mocked').persist().get('/').reply(200, 'foo'); }); after(() => { // scope.persist(false); // This causes the Bar tests to use the Foo nocks one more time :( // nock.cleanAll(); // This also disables the common nocks }); it('Should get FOO', async () => { expect(await fetch('http://mocked').then(res => res.text())).to.equal('foo'); expect(await fetch('http://common').then(res => res.text())).to.equal('common'); }); it('Should get FOO again', async () => { expect(await fetch('http://mocked').then(res => res.text())).to.equal('foo'); expect(await fetch('http://common').then(res => res.text())).to.equal('common'); }); }); describe('Bar tests', () => { let scope; before(async () => { scope = nock('http://mocked').persist().get('/').reply(200, 'bar'); }); after(() => { // scope.persist(false); // nock.cleanAll(); }); it('Should get BAR', async () => { expect(await fetch('http://mocked').then(res => res.text())).to.equal('bar'); expect(await fetch('http://common').then(res => res.text())).to.equal('common'); }); it('Should get BAR again', async () => { expect(await fetch('http://mocked').then(res => res.text())).to.equal('bar'); expect(await fetch('http://common').then(res => res.text())).to.equal('common'); }); });

[如果使用scope.persist(false),这些测试将使第三项测试失败(因为该测试仍获得foo版本),或者如果使用了nock.cleanAll(),则这些测试将失败3和4,因为然后删除了公用标记。

使用nock,有没有办法禁用单个nock范围?我一直在努力进行一些测试,这些测试设置了与其他测试相同的URL标记。它们都可以单独运行,但是在...

node.js mocha nock
1个回答
0
投票
我也遇到了这个问题,并找到了一种解决方法,方法是监听示波器发出的request事件,并在触发该事件时删除拦截器。理想情况下,我认为您应该收听replied事件,但是由于某种原因,当我尝试该事件时并未触发该事件,不确定原因。但是下面的代码对我有用:
© www.soinside.com 2019 - 2024. All rights reserved.