Skip to content
Advertisement

How to mock functions in the same module using Jest?

What’s the best way to correctly mock the following example?

The problem is that after import time, foo keeps the reference to the original unmocked bar.

module.js:

JavaScript

module.test.js:

JavaScript

I could change:

JavaScript

to:

JavaScript

but this is pretty ugly in my opinion to do everywhere.

Advertisement

Answer

fwiw, the solution I settled on was to use dependency injection, by setting a default argument.

So I would change

JavaScript

to

JavaScript

This is not a breaking change to the API of my component, and I can easily override bar in my test by doing the following

JavaScript

This has the benefit of leading to slightly nicer test code too 🙂

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement