Mastering Jest: How to Mock Specific Functions in Modules
Written on
Chapter 1: Understanding Jest Mocking
For quite some time, I found Jest to be quite perplexing. The process of mocking was particularly challenging, and locating the right documentation felt like a daunting task. However, after extensive practice and taking notes on Notion, I managed to overcome my difficulties and became proficient with Jest.
In this article, we will concentrate on the method of mocking a specific function or variable from a module. The approach involves importing the complete module using jest.requireActual, then spreading it into a new object that contains the mocked values.
Let's delve deeper into this:
const originalModule = jest.requireActual('../my-module');
In this line, we are loading the actual module without applying any mocks. This step allows us to inject values that we want to retain as the originals.
...originalModule
Here, we are incorporating the original values and functions into our new object.
_esModule: true
This indicates to JavaScript that we are indeed dealing with a module.
default: () => 'foo'
In this scenario, we are mocking the default export of the module. This is applicable only if you are using a default export; otherwise, you would skip it.
foo: () => 'bar',
In this instance, we are altering the function foo to return 'bar'.
toto: 'tata'
Ultimately, we are modifying the exported value toto to be 'tata'. This method of changing a value is also applicable to constant variables since it doesn't alter their original value; it generates a new one.
Mocking in Jest becomes quite manageable once you identify and understand the appropriate documentation and tutorials. As illustrated, it only takes a few lines of code to achieve the desired outcome!
I hope you found this article helpful. Feel free to follow for more insights!
You can find additional resources at PlainEnglish.io. Subscribe to our free weekly newsletter, and connect with us on Twitter and LinkedIn. Join our community on Discord.
Chapter 2: Practical Examples of Jest Mocking
The first video titled "Testing React #7: Mocking modules with Jest" provides a thorough exploration of how to effectively mock modules in Jest, enhancing your understanding of this crucial testing technique.
The second video, "Mock vs Spy in Testing with Jest: Which is Better?", compares these two vital techniques for function testing, helping you decide the best approach for your projects.