Ensure all nock mock interceptors are used

09 Jan 2021 in TIL

When using nock to mock HTTP requests in node, you can call nock.disableNetConnect() to make nock throw an error any time a request is made that does not have a mock configured. This is useful, but only tells half of the story. What happens if you configure a mock that is not used? Your application/library may not be making a request that you expect it to.

I use jest for testing, but the following instructions would work for tools such as mocha too.

nock exposes a few useful functions that we can use to keep track of our configured mocks:

  • isDone - returns true if all configured mocks have been used
  • pendingMocks - returns any mocks that have been configured but not called
  • cleanAll - removes all active mocks (both pending and fulfilled)

Putting these three functions together, we can add an afterEach method to our tests that show an error if there are any pendingMocks remaining:

javascript
afterEach(() => {
if (!nock.isDone()) {
throw new Error(
`Not all nock interceptors were used: ${JSON.stringify(
nock.pendingMocks()
)}`
);
}
nock.cleanAll();
});

This will throw an error if there are any unused mocks and log out the HTTP verb, host and path for any pending mocks (e.g. ["GET http://example.com:80/path"])