Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: How to globally mock node-uuid (or any other imported module)

Recently migrated from mocha to jest and I'm running into an issue. I have lots of warnings in my tests:

[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()

Now, adding the following line to each file fixes the issue, but only for that specific test file:

jest.mock('node-uuid', () => ({ v4: jest.fn(() => 1) }));

I'm hoping there's a way to mock node-uuid globally for all tests instead of individual files? I've done a bunch of searches and tried different techniques in my setup file, but to no avail.

like image 750
Justin Schrader Avatar asked Nov 25 '17 15:11

Justin Schrader


People also ask

How do you mock a node Jest module?

Mocking Node modules​ If the module you are mocking is a Node module (e.g.: lodash ), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.

Are Jest mocks Global?

If you need to mock a global variable for all of your tests, you can use the setupFiles in your Jest config and point it to a file that mocks the necessary variables. This way, you will have the global variable mocked globally for all test suites.

How do you mock an import Jest?

To mock an imported function with Jest we use the jest. mock() function. jest. mock() is called with one required argument - the import path of the module we're mocking.

How do you mock a node?

In Jest, Node. js modules are automatically mocked in your tests when you place the mock files in a __mocks__ folder that's next to the node_modules folder. For example, if you a file called __mock__/fs. js , then every time the fs module is called in your test, Jest will automatically use the mocks.


1 Answers

You can define a manual-mock in the [root]/__mocks__/node-uuid.js where [root] is the directory where the node_modules directory is located:

module.exports = { v4: jest.fn(() => 1) }
like image 158
Fathy Avatar answered Nov 12 '22 03:11

Fathy