Automocking
In this (very short) optional lesson, learn one more way to mock modules in your code.
We'll cover the following
Automocking
You noticed that, to mock a module, we had to write:
jest.mock('module name');
However, there is one more approach that makes even this line unnecessary.
Note: I show you this approach merely for informative purposes, but I myself have never found it useful in production projects due to its nature. If you do end up using it somewhere, do let me know about your experiences in the course discussion!
If you open the file setupTests.js
and add this line to it:
jest.enableAutomock();
You will enable automocking across all test code. What is automocking and how is it different from jest.mock
?
Automocking mocks every single import in testing code and replaces it with either a jest.fn()
or a specified mock from __mocks__
folder. To actually test something, you would have to unmock a module so you can actually access that code:
import MyComponent from './MyComponent';
// MyComponent is currently mocked
// To test it, you need to add
jest.unmock('./MyComponent');
// now you can test it
The upside of this approach is its simplicity and safety. You do not have to worry about mocking API functions because all functions are already mocked.
The downside of this approach is un-mocking everything you want to test and configuring the mocks you decide to leave mocked. While mocking is essential, clean coding practices should keep such unbreakable dependencies to a minimum. If you start relying on mocks so much that automocking becomes viable, there may be a bigger problem in your code.
Get hands-on with 1400+ tech skills courses.