DEV Community

Brian
Brian

Posted on • Updated on

Mocking Modules with Jest

Alt Text

The other day I posted how frustrated I was with mocking a custom module with Jest. https://twitter.com/brianmcoates/status/1182097590126628864

Alt Text

What I found was in Jest when setting up a custom mock you need to pass the function you are wanting to mock to jest.mock() not the mock that you have created but the actual custom module which is ultimately a function.

If you are also using a function on your MOCK to set the context in your tests you will need to import the actual function you are mocking in your tests that you are writing.

Below is an example of importing and using a custom module in one of my tests.

import uuid from '../utilities/uuid';
jest.mock('../utilities/uuid');

If you aren't setting context or needing to set up the function in anyway you can just get away with doing nothing! IF you make sure your mocks are living in the right place.

The key here is you have to place your mock adjacent to your custom module. There is an example below and here is the Jest documentation on that as well. https://jestjs.io/docs/en/manual-mocks.html

.
├── utilities
│ ├── mocks
│ │ └── uuid.js
│ └── uuid.js
├── node_modules
└── views

Hope this was helpful.

Top comments (0)