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. Note that the mocks folder is case-sensitive, so naming the directory MOCKS will break on some systems.

When we require that module in our tests, 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 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.

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

例子

  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, manual mocks will take precedence over node modules 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.

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.

  1. // FileSummarizer.js
  2. 'use strict';
  3. const fs = require('fs');
  4. function summarizeFilesInDirectorySync(directory) {
  5. return fs.readdirSync(directory).map(fileName => ({
  6. directory,
  7. fileName,
  8. }));
  9. }
  10. 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:

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

Now we write our test. Note that we need to explicitly tell that we want to mock the fs module because it’s a core Node module:

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

The example mock shown here uses jest.genMockFromModule 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.