DEV Community

Michael Heap
Michael Heap

Posted on • Originally published at michaelheap.com on

Ensure all nock mock interceptors are used

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:

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

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"])

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs