【发布时间】:2023-04-09 18:08:01
【问题描述】:
使用nock,有没有办法禁用单个诺克范围? 我一直在努力进行一些设置与其他测试相同 URL 的 nocks 的测试。它们都单独运行良好,但是当在同一个 mocha 会话中运行时,其中一个会失败,因为我无法重新锁定活动的 nock 范围,这意味着设置的 nocks 会捕获所有请求。
我尝试过的:
- 如果我在
before()中设置了一些nocks,然后在我的after()中调用scope.persist(false),它只会“取消保留”范围,以便它对一个请求有效。它不会立即禁用它。 - 我发现
nock.cleanAll()会立即禁用 nocks,以便可以再次设置它们,但随后它也禁用可能已经设置过一次的所有全局 nocks,对所有测试用例。
到目前为止,我发现的唯一解决方案是 1) 对所有 nocks 使用唯一的 URL:s,这并不总是可行的,或者 2) 使用 nock.cleanAll() 并且不依赖任何全局 nocks -而是确保只在本地 before() 函数中设置 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),这些测试要么在第 3 次测试中失败(因为该测试仍然获得 foo 版本),或者如果使用 nock.cleanAll(),则在第 3 次和第 4 次测试中失败,因为随后移除了常见的 nocks。
【问题讨论】: