nock / nock

HTTP server mocking and expectations library for Node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Interceptors not being removed in 13.3.2

zakwalters opened this issue · comments

commented

Please avoid duplicates

Reproducible test case

See description

Nock Version

13.3.2

Node Version

18.17.0

TypeScript Version

5.1.6

What happened?

Interceptors aren't being removed in the same way following #2497. #2500 is also reporting an issue with 13.3.2 but it doesn't mention removeInterceptor so I don't believe the issues are the same.

We have a file that sets up a bunch of default mock responses using nock. In some tests, we needed to remove these using removeInterceptor. Because the interceptors were defined in another file, we couldn't easily pass the interceptor object, so instead we constructed an equivalent one, and removeInterceptor behaved as we wanted. When upgrading to 13.3.2 from 13.3.1, this broke.

import nock from 'nock';

nock('https://some-url').get('/some-path').reply(200);
console.log(nock.pendingMocks());
// In both 13.3.1 and 13.3.2 this outputs
// [ 'GET https://some-url:443/some-path' ]

nock.removeInterceptor(nock('https://some-url').get('/some-path'));
console.log(nock.pendingMocks());
// In 13.3.1 this outputs:
// []
// But in 13.3.2 it outputs:
// [ 'GET https://some-url:443/some-path' ]

While looking for workarounds, I also noticed that there doesn't seem to be a good way to remove an interceptor with a regex URI by passing a ReqOptions object to removeInterceptor instead of an Interceptor:

nock('https://some-url').get(/some-regex-path/).reply(200);
nock.removeInterceptor({ host: 'https://some-url', path: /some-regex-path/});
// Type 'RegExp' is not assignable to type 'string'.ts(2322)

From a brief look at the source and the output of pendingMocks for regex interceptors, it seems like it should be possible to convert options.key to a string if it's a regex, and allow removal in this way. Maybe it's more complex than I realise, but it would be a nice feature if not.


A final, somewhat tangential point: the link in this prompt from the issue template is still using nock/nock.js when I believe it should be nock/nock, so it's a 404:

I checked all open bugs and none of them matched my problem.

Would you be interested in contributing a fix?

  • yes

a pull request would be very welcome. Ideally we would add a test that would prevent a regression like this from happening again

Potential duplication: #2353