Manual Mocks

Manual mocks are used to stub out functionality with mock data. For example, instead of accessing a remote resource like a website or a database, you might want to create a manual mock that allows you to use fake data. This ensures your tests will be fast and not flaky.

Mocking user modules

Manual mocks are defined by writing a module in a __mocks__/ subdirectory immediately adjacent to the module. For example, to mock a module called user in the models directory, create a file called user.js and put it in the models/__mocks__ directory.

Manual Mocks - 图1caution

The __mocks__ folder is case-sensitive, so naming the directory __MOCKS__ will break on some systems.

Manual Mocks - 图2note

When we require that module in our tests (meaning we want to use the manual mock instead of the real implementation), explicitly calling jest.mock('./moduleName') is required.

Mocking Node modules

If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There’s no need to explicitly call jest.mock('module_name').

Scoped modules (also known as scoped packages) can be mocked by creating a file in a directory structure that matches the name of the scoped module. For example, to mock a scoped module called @scope/project-name, create a file at __mocks__/@scope/project-name.js, creating the @scope/ directory accordingly.

Manual Mocks - 图3caution

If we want to mock Node’s built-in modules (e.g.: fs or path), then explicitly calling e.g. jest.mock('path') is required, because built-in modules are not mocked by default.

Examples

  1. .
  2. ├── config
  3. ├── __mocks__
  4. └── fs.js
  5. ├── models
  6. ├── __mocks__
  7. └── user.js
  8. └── user.js
  9. ├── node_modules
  10. └── views

When a manual mock exists for a given module, Jest’s module system will use that module when explicitly calling jest.mock('moduleName'). However, when automock is set to true, the manual mock implementation will be used instead of the automatically created mock, even if jest.mock('moduleName') is not called. To opt out of this behavior you will need to explicitly call jest.unmock('moduleName') in tests that should use the actual module implementation.

Manual Mocks - 图4info

In order to mock properly, Jest needs jest.mock('moduleName') to be in the same scope as the require/import statement.

Here’s a contrived example where we have a module that provides a summary of all the files in a given directory. In this case, we use the core (built in) fs module.

FileSummarizer.js

  1. 'use strict';
  2. const fs = require('fs');
  3. function summarizeFilesInDirectorySync(directory) {
  4. return fs.readdirSync(directory).map(fileName => ({
  5. directory,
  6. fileName,
  7. }));
  8. }
  9. exports.summarizeFilesInDirectorySync = summarizeFilesInDirectorySync;

Since we’d like our tests to avoid actually hitting the disk (that’s pretty slow and fragile), we create a manual mock for the fs module by extending an automatic mock. Our manual mock will implement custom versions of the fs APIs that we can build on for our tests:

__mocks__/fs.js

  1. 'use strict';
  2. const path = require('path');
  3. const fs = jest.createMockFromModule('fs');
  4. // This is a custom function that our tests can use during setup to specify
  5. // what the files on the "mock" filesystem should look like when any of the
  6. // `fs` APIs are used.
  7. let mockFiles = Object.create(null);
  8. function __setMockFiles(newMockFiles) {
  9. mockFiles = Object.create(null);
  10. for (const file in newMockFiles) {
  11. const dir = path.dirname(file);
  12. if (!mockFiles[dir]) {
  13. mockFiles[dir] = [];
  14. }
  15. mockFiles[dir].push(path.basename(file));
  16. }
  17. }
  18. // A custom version of `readdirSync` that reads from the special mocked out
  19. // file list set via __setMockFiles
  20. function readdirSync(directoryPath) {
  21. return mockFiles[directoryPath] || [];
  22. }
  23. fs.__setMockFiles = __setMockFiles;
  24. fs.readdirSync = readdirSync;
  25. module.exports = fs;

Now we write our test. In this case jest.mock('fs') must be called explicitly, because fs is Node’s built-in module:

__tests__/FileSummarizer-test.js

  1. 'use strict';
  2. jest.mock('fs');
  3. describe('listFilesInDirectorySync', () => {
  4. const MOCK_FILE_INFO = {
  5. '/path/to/file1.js': 'console.log("file1 contents");',
  6. '/path/to/file2.txt': 'file2 contents',
  7. };
  8. beforeEach(() => {
  9. // Set up some mocked out file info before each test
  10. require('fs').__setMockFiles(MOCK_FILE_INFO);
  11. });
  12. test('includes all files in the directory in the summary', () => {
  13. const FileSummarizer = require('../FileSummarizer');
  14. const fileSummary =
  15. FileSummarizer.summarizeFilesInDirectorySync('/path/to');
  16. expect(fileSummary.length).toBe(2);
  17. });
  18. });

The example mock shown here uses jest.createMockFromModule to generate an automatic mock, and overrides its default behavior. This is the recommended approach, but is completely optional. If you do not want to use the automatic mock at all, you can export your own functions from the mock file. One downside to fully manual mocks is that they’re manual – meaning you have to manually update them any time the module they are mocking changes. Because of this, it’s best to use or extend the automatic mock when it works for your needs.

To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using jest.requireActual(moduleName) in your manual mock and amending it with mock functions before exporting it.

The code for this example is available at examples/manual-mocks.

Using with ES module imports

If you’re using ES module imports then you’ll normally be inclined to put your import statements at the top of the test file. But often you need to instruct Jest to use a mock before modules use it. For this reason, Jest will automatically hoist jest.mock calls to the top of the module (before any imports). To learn more about this and see it in action, see this repo.

Manual Mocks - 图5caution

jest.mock calls cannot be hoisted to the top of the module if you enabled ECMAScript modules support. The ESM module loader always evaluates the static imports before executing code. See ECMAScriptModules for details.

Mocking methods which are not implemented in JSDOM

If some code uses a method which JSDOM (the DOM implementation used by Jest) hasn’t implemented yet, testing it is not easily possible. This is e.g. the case with window.matchMedia(). Jest returns TypeError: window.matchMedia is not a function and doesn’t properly execute the test.

In this case, mocking matchMedia in the test file should solve the issue:

  1. Object.defineProperty(window, 'matchMedia', {
  2. writable: true,
  3. value: jest.fn().mockImplementation(query => ({
  4. matches: false,
  5. media: query,
  6. onchange: null,
  7. addListener: jest.fn(), // deprecated
  8. removeListener: jest.fn(), // deprecated
  9. addEventListener: jest.fn(),
  10. removeEventListener: jest.fn(),
  11. dispatchEvent: jest.fn(),
  12. })),
  13. });

This works if window.matchMedia() is used in a function (or method) which is invoked in the test. If window.matchMedia() is executed directly in the tested file, Jest reports the same error. In this case, the solution is to move the manual mock into a separate file and include this one in the test before the tested file:

  1. import './matchMedia.mock'; // Must be imported before the tested file
  2. import {myMethod} from './file-to-test';
  3. describe('myMethod()', () => {
  4. // Test the method here...
  5. });