DEV Community

Brian
Brian

Posted on • Edited on

2

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →