jpenna
jpenna

Reputation: 9191

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__.

Upvotes: 4

Views: 4726

Answers (1)

Andreas Köberle
Andreas Köberle

Reputation: 110932

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.

Upvotes: 7

Related Questions