问题
I am using nock and I'm trying to remove interceptors for certain hostname.
I have tried using:
nock.removeInterceptor({
hostname: 'somehostname.com',
proto: 'https',
path: '/',
}),
When I print the result of this, it actually gives me true
I have also tried:
const mock = nock(somehostname.com)
.persist()
.post('/endpoint')
.reply(200);
nock.removeInterceptor(mock)
But this gives me false somehow.
The way I'm checking if this is working is by printing the activeMocks:
nock.activeMocks()
And it still has the interceptors that I'm trying to remove.
Does anyone know what happens?
回答1:
I'd got the same problem and I solved like this:
const mock = nock(somehostname.com)
.persist()
.post('/endpoint')
.reply(200);
nock.removeInterceptor(mock.interceptors[0])
mock.interceptors
is a array of all Interceptor object registered for this scope, so I get the most recently created scope and remove it from nock.
回答2:
It appears that nock uses singletons underneath and that calling nock("my/base-route/i/already/mocked")
returns the scope which can then be used to query the interceptor again by using scope.get("my/endpoint/I/already/mocked")
, which returns the interceptor. This interceptor can then be removed using nock.removeInterceptor(interceptor)
which should return true
.
So in total:
function mockRoute() {
nock("my/base-route/i/already/mocked")
.get("my/endpoint/I/already/mocked")
.reply("Something")
}
function removeExistingMock(): boolean {
const scope = nock("my/base-route/i/already/mocked")
const interceptor = scope.get("my/endpoint/I/already/mocked")
return nock.removeInterceptor(interceptor)
}
来源:https://stackoverflow.com/questions/57073358/unable-to-remove-interceptors-using-nock