'how do you mock out node_modules package in jest unit test?

I have an Nx workspace with a library it in that has a unit test that needs to mock a node_module package.

One example is unit testing our interface with Stripe. I have built a mock implementation of the stripe-js that I have npm added to my project.

Without Nx, I would put the stripe-js.ts mock file in the mock folder that is next to the top level src file.

I have tried putting this mock folder beside the workspace folder, but it isn't being picked up by jest.

Where should this mock folder be placed when unit testing in a library?

myorg/
 ├── __mocks__/
 |    ├── stripe-js.js
 ├── apps/
 |    ├── myapp
 ├── libs/
 |    └── lib1
 |        ├── test.spec.js
 ├── node_modules

Without Nx, it should be placed in the diagram above, but I am not sure where it should be placed when unit testing lib1.



Solution 1:[1]

I was helped out on Slack by an Nx user who had figured out how to do this.

The trick comes in two parts:

  1. The location of the mocks directory is the root of your workspace (ie, beside the node_modules directory
  2. The second part is to modify your jest.preset.js file in the root of your workspace to add a roots entry:
const nxPreset = require('@nrwl/jest/preset').default;
const path = require('path');

module.exports = {
  ...nxPreset,
  roots: ["<rootDir>", path.resolve(__dirname, "./__mocks__")]
 };

With the roots entry pointing to the mocks directory, jest will then pick up the automatic mocks for node_module packages.

And for completness, if you want to mock out something like a package called stripe-js, you would create a file in workspace/__mocks__ called stripe-js.js and in that file you would put your mock implementation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Greg Veres