Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a module for only one test file with Jest?

I am using Jest and I want to mock some functions from another module (let's call it dependency).

I was able to mock dependency globally, putting it inside a __mocks__ folder inside my __tests__ folder.

Unfortunately, I need the actual dependecy for all the other tests. So, how can I specify that I want to require the mocked dependecy only when required in my file1.js, but not in all other files?

PS: I could create a __mocks__ folder inside my file1.js folder, but this file is in the root, so when dependency is required by any file it will be picked up from the __mocks__.

like image 935
jpenna Avatar asked Oct 28 '25 05:10

jpenna


1 Answers

You need to use jest.mock:

jest.mock('path/to/dependency', () => 'someMockValue')

Note that the path is relative to the test file, not to the file you want test.

like image 63
Andreas Köberle Avatar answered Oct 30 '25 05:10

Andreas Köberle