Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jestjs

nock

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.

like image 887
Nathan Arthur Avatar asked Oct 22 '25 07:10

Nathan Arthur


1 Answers

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).

like image 179
Nathan Arthur Avatar answered Oct 27 '25 04:10

Nathan Arthur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!