Unable to remove interceptors using nock

半腔热情 提交于 2020-12-06 12:32:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!