jest-environment-nock-axios
Mock all network requests in tests using nock.
Purpose
This environment ensures that no unmocked network requests are made (by calling nock's disableNetConnect). It also takes care of some additional setup required to support axios.
Installation
Install as usual with npm install -D jest-environment-nock-axios
(or the yarn
equivalent). Both
nock and axios are required as peer dependencies.
To run a test in this environment set the testEnvironment option.
Gotchas
Jest by design doesn't implement the require cache. This means that the nock module configured by the environment is different from the module your tests get. To solve this that instance is injected into the global scope (see the example below).
Tips
It's a good idea to verify test that no mocked requests are pending. One way to do that is to run the
following code after each test (e.g. using Jest's
setupFilesAfterEnv
) config option:
const nock = globalnock; // See the 'Gotcha' section above ;
Example
/** * @jest-environment nock-axios */; describe'This test',