jestjsnock

How do I use Nock to disable all external API requests during testing?


I'm testing a codebase that makes external requests to multiple APIs. How do I ensure that a request is never made to one of these APIs during testing? I already plan to use Nock for mocking responses, but I'm worried I'll forget to mock a response and a request will go to the live API.


Solution

  • Nock includes a feature specifically for this purpose. To use it with Jest, first ensure that you've configured Jest to use a setup file. You can do this by adding the following to package.json:

    "jest": {
      "setupFiles": ["./jest.setup.js"]
    },
    

    Then add the following code to the new setup file:

    import * as nock from 'nock';
    nock.disableNetConnect();
    

    From now on, any unmocked network requests sent during test run will fail with an error similar to this:

    FetchError: request to https://my-api.io/endpoint failed, reason: Nock: Disallowed net connect for "my-api.io/endpoint"

    Note this only intercepts HTTP requests, not other network I/O (under the hood it mocks http.ClientRequest).