DEV Community

Rafael Lourenço
Rafael Lourenço

Posted on

Custom Paths for mocks Folder in Monorepo using Jest

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.

Morse Mock

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', 
  },
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

And our mock tests are well-exported.

const mockAdd = jest.fn((a, b) => a + b);

module.exports = mockAdd;

Enter fullscreen mode Exit fullscreen mode

If your tests are correct, this should be the result.

Test Pass

Top comments (0)