Imagine you have a monorepo with tons of repositories. For each repository, you encounter the same issue: a need to maintain an identical mock in each repository. Whenever you update one, you must manually update all the others. This can result in a significant waste of your time.
You have a good idea to place your mock at the root level for importing into all tests as needed. While this approach works, it introduces a new small problem: Your imports can become like Morse code, especially if your tests are deeply nested.
To solve that, we're going to create a custom path for your mocks folder inside your Jest configuration for each repository in your monorepo.
moduleNameMapper: {
'^@mocks/(.*)$': '<rootDir>/<your_path_to_your_mock_folder>/$1',
},
And now, we can import our mock inside each test using this syntax:
const mockAdd = require('@mocks/math');
test('uses mockAdd to add 1 + 2 to equal 3', () => {
expect(mockAdd(1, 2)).toBe(3);
});
And our mock tests are well-exported.
const mockAdd = jest.fn((a, b) => a + b);
module.exports = mockAdd;
If your tests are correct, this should be the result.
Top comments (0)