The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest's overall behavior.

Mock Modules

jest.disableAutomock()

Disables automatic mocking in the module loader.

See automock section of configuration for more information

After this method is called, all require()s will return the real versions of each module (rather than a mocked version).

Jest configuration:

  1. {
  2. "automock": true
  3. }

示例:

  1. // utils.js
  2. export default {
  3. authorize: () => {
  4. return 'token';
  5. },
  6. };
  1. // __tests__/disableAutomocking.js
  2. import utils from '../utils';
  3. jest.disableAutomock();
  4. test('original implementation', () => {
  5. // now we have the original implementation,
  6. // even if we set the automocking in a jest configuration
  7. expect(utils.authorize()).toBe('token');
  8. });

This is usually useful when you have a scenario where the number of dependencies you want to mock is far less than the number of dependencies that you don't. For example, if you're writing a test for a module that uses a large number of dependencies that can be reasonably classified as "implementation details" of the module, then you likely do not want to mock them.

Examples of dependencies that might be considered "implementation details" are things ranging from language built-ins (e.g. Array.prototype methods) to highly common utility methods (e.g. underscore/lo-dash, array utilities etc) and entire libraries like React.js.

Returns the jest object for chaining.

Note: this method was previously called autoMockOff. When using babel-jest, calls to disableAutomock will automatically be hoisted to the top of the code block. Use autoMockOff if you want to explicitly avoid this behavior.

jest.enableAutomock()

Enables automatic mocking in the module loader.

Returns the jest object for chaining.

See automock section of configuration for more information

示例:

  1. // utils.js
  2. export default {
  3. authorize: () => {
  4. return 'token';
  5. },
  6. isAuthorized: secret => secret === 'wizard',
  7. };
  1. // __tests__/disableAutomocking.js
  2. jest.enableAutomock();
  3. import utils from '../utils';
  4. test('original implementation', () => {
  5. // now we have the mocked implementation,
  6. expect(utils.authorize._isMockFunction).toBeTruthy();
  7. expect(utils.isAuthorized._isMockFunction).toBeTruthy();
  8. });

Note: this method was previously called autoMockOn. When using babel-jest, calls to enableAutomock will automatically be hoisted to the top of the code block. Use autoMockOn if you want to explicitly avoid this behavior.

jest.genMockFromModule(moduleName)

Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you.

This is useful when you want to create a manual mock that extends the automatic mock's behavior.

示例:

  1. // utils.js
  2. export default {
  3. authorize: () => {
  4. return 'token';
  5. },
  6. isAuthorized: secret => secret === 'wizard',
  7. };
  1. // __tests__/genMockFromModule.test.js
  2. const utils = jest.genMockFromModule('../utils').default;
  3. utils.isAuthorized = jest.fn(secret => secret === 'not wizard');
  4. test('implementation created by jest.genMockFromModule', () => {
  5. expect(utils.authorize.mock).toBeTruthy();
  6. expect(utils.isAuthorized('not wizard')).toEqual(true);
  7. });

This is how genMockFromModule will mock the following data types:

函数

Creates a new mock function. The new function has no formal parameters and when called will return undefined. This functionality also applies to async functions.

Class

Creates new class. The interface of the original class is maintained, all of the class member functions and properties will be mocked.

对象

Creates a new deeply cloned object. The object keys are maintained and their values are mocked.

数组

Creates a new empty array, ignoring the original.

Primitives

Creates a new property with the same primitive value as the original property.

示例:

  1. // example.js
  2. module.exports = {
  3. function: function square(a, b) {
  4. return a * b;
  5. },
  6. asyncFunction: async function asyncSquare(a, b) {
  7. const result = await a * b;
  8. return result;
  9. },
  10. class: new class Bar {
  11. constructor() {
  12. this.array = [1, 2, 3];
  13. }
  14. foo() {}
  15. },
  16. object: {
  17. baz: 'foo',
  18. bar: {
  19. fiz: 1,
  20. buzz: [1, 2, 3],
  21. },
  22. },
  23. array: [1, 2, 3],
  24. number: 123,
  25. string: 'baz',
  26. boolean: true,
  27. symbol: Symbol.for('a.b.c'),
  28. };
  1. // __tests__/example.test.js
  2. const example = jest.genMockFromModule('./example');
  3. test('should run example code', () => {
  4. // creates a new mocked function with no formal arguments.
  5. expect(example.function.name).toEqual('square');
  6. expect(example.function.length).toEqual(0);
  7. // async functions get the same treatment as standard synchronous functions.
  8. expect(example.asyncFunction.name).toEqual('asyncSquare');
  9. expect(example.asyncFunction.length).toEqual(0);
  10. // creates a new class with the same interface, member functions and properties are mocked.
  11. expect(example.class.constructor.name).toEqual('Bar');
  12. expect(example.class.foo.name).toEqual('foo');
  13. expect(example.class.array.length).toEqual(0);
  14. // creates a deeply cloned version of the original object.
  15. expect(example.object).toEqual({
  16. baz: 'foo',
  17. bar: {
  18. fiz: 1,
  19. buzz: [],
  20. },
  21. });
  22. // creates a new empty array, ignoring the original array.
  23. expect(example.array.length).toEqual(0);
  24. // creates a new property with the same primitive value as the original property.
  25. expect(example.number).toEqual(123);
  26. expect(example.string).toEqual('baz');
  27. expect(example.boolean).toEqual(true);
  28. expect(example.symbol).toEqual(Symbol.for('a.b.c'));
  29. });

jest.mock(moduleName, factory, options)

Mocks a module with an auto-mocked version when it is being required. factory and options are optional. 例如:

  1. // banana.js
  2. module.exports = () => 'banana';
  3. // __tests__/test.js
  4. jest.mock('../banana');
  5. const banana = require('../banana'); // banana will be explicitly mocked.
  6. banana(); // will return 'undefined' because the function is auto-mocked.

The second argument can be used to specify an explicit module factory that is being run instead of using Jest's automocking feature:

  1. jest.mock('../moduleName', () => {
  2. return jest.fn(() => 42);
  3. });
  4. // This runs the function specified as second argument to `jest.mock`.
  5. const moduleName = require('../moduleName');
  6. moduleName(); // Will return '42';

When using the factory parameter for an ES6 module with a default export, the __esModule: true property needs to be specified. This property is normally generated by Babel / TypeScript, but here it needs to be set manually. When importing a default export, it's an instruction to import the property named default from the export object:

  1. import moduleName, {foo} from '../moduleName';
  2. jest.mock('../moduleName', () => {
  3. return {
  4. __esModule: true,
  5. default: jest.fn(() => 42),
  6. foo: jest.fn(() => 43),
  7. };
  8. });
  9. moduleName(); // Will return 42
  10. foo(); // Will return 43

The third argument can be used to create virtual mocks – mocks of modules that don't exist anywhere in the system:

  1. jest.mock(
  2. '../moduleName',
  3. () => {
  4. /*
  5. * Custom implementation of a module that doesn't exist in JS,
  6. * like a generated module or a native module in react-native.
  7. */
  8. },
  9. {virtual: true},
  10. );

Warning: Importing a module in a setup file (as specified by setupTestFrameworkScriptFile) will prevent mocking for the module in question, as well as all the modules that it imports.

Modules that are mocked with jest.mock are mocked only for the file that calls jest.mock. Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module.

Returns the jest object for chaining.

jest.unmock(moduleName)

Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module).

The most common use of this API is for specifying the module a given test intends to be testing (and thus doesn't want automatically mocked).

Returns the jest object for chaining.

jest.doMock(moduleName, factory, options)

When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.

One example when this is useful is when you want to mock a module differently within the same file:

  1. beforeEach(() => {
  2. jest.resetModules();
  3. });
  4. test('moduleName 1', () => {
  5. jest.doMock('../moduleName', () => {
  6. return jest.fn(() => 1);
  7. });
  8. const moduleName = require('../moduleName');
  9. expect(moduleName()).toEqual(1);
  10. });
  11. test('moduleName 2', () => {
  12. jest.doMock('../moduleName', () => {
  13. return jest.fn(() => 2);
  14. });
  15. const moduleName = require('../moduleName');
  16. expect(moduleName()).toEqual(2);
  17. });

Using jest.doMock() with ES6 imports requires additional steps. Follow these if you don't want to use require in your tests:

  • We have to specify the __esModule: true property (see the jest.mock() API for more information).
  • Static ES6 module imports are hoisted to the top of the file, so instead we have to import them dynamically using import().
  • Finally, we need an environment which supports dynamic importing. Please see Using Babel for the initial setup. Then add the plugin babel-plugin-dynamic-import-node, or an equivalent, to your Babel config to enable dynamic importing in Node.
  1. beforeEach(() => {
  2. jest.resetModules();
  3. });
  4. test('moduleName 1', () => {
  5. jest.doMock('../moduleName', () => {
  6. return {
  7. __esModule: true,
  8. default: 'default1',
  9. foo: 'foo1',
  10. };
  11. });
  12. return import('../moduleName').then(moduleName => {
  13. expect(moduleName.default).toEqual('default1');
  14. expect(moduleName.foo).toEqual('foo1');
  15. });
  16. });
  17. test('moduleName 2', () => {
  18. jest.doMock('../moduleName', () => {
  19. return {
  20. __esModule: true,
  21. default: 'default2',
  22. foo: 'foo2',
  23. };
  24. });
  25. return import('../moduleName').then(moduleName => {
  26. expect(moduleName.default).toEqual('default2');
  27. expect(moduleName.foo).toEqual('foo2');
  28. });
  29. });

Returns the jest object for chaining.

jest.dontMock(moduleName)

When using babel-jest, calls to unmock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.

Returns the jest object for chaining.

jest.setMock(moduleName, moduleExports)

Explicitly supplies the mock object that the module system should return for the specified module.

On occasion there are times where the automatically generated mock the module system would normally provide you isn't adequate enough for your testing needs. Normally under those circumstances you should write a manual mock that is more adequate for the module in question. However, on extremely rare occasions, even a manual mock isn't suitable for your purposes and you need to build the mock yourself inside your test.

In these rare scenarios you can use this API to manually fill the slot in the module system's mock-module registry.

Returns the jest object for chaining.

Note It is recommended to use jest.mock() instead. The jest.mock API's second argument is a module factory instead of the expected exported module object.

jest.requireActual(moduleName)

Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.

示例:

  1. jest.mock('../myModule', () => {
  2. // Require the original module to not be mocked...
  3. const originalModule = jest.requireActual(moduleName);
  4. return {
  5. __esModule: true, // Use it when dealing with esModules
  6. ...originalModule,
  7. getRandom: jest.fn().mockReturnValue(10),
  8. };
  9. });
  10. const getRandom = require('../myModule').getRandom;
  11. getRandom(); // Always returns 10

jest.requireMock(moduleName)

Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.

jest.resetModules()

Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests.

示例:

  1. const sum1 = require('../sum');
  2. jest.resetModules();
  3. const sum2 = require('../sum');
  4. sum1 === sum2;
  5. // > false (Both sum modules are separate "instances" of the sum module.)

Example in a test:

  1. beforeEach(() => {
  2. jest.resetModules();
  3. });
  4. test('works', () => {
  5. const sum = require('../sum');
  6. });
  7. test('works too', () => {
  8. const sum = require('../sum');
  9. // sum is a different copy of the sum module from the previous test.
  10. });

Returns the jest object for chaining.

jest.isolateModules(fn)

jest.isolateModules(fn) goes a step further than jest.resetModules() and creates a sandbox registry for the modules that are loaded inside the callback function. This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests.

  1. let myModule;
  2. jest.isolateModules(() => {
  3. myModule = require('myModule');
  4. });
  5. const otherCopyOfMyModule = require('myModule');

Mock functions

jest.fn(implementation)

Returns a new, unused mock function. Optionally takes a mock implementation.

  1. const mockFn = jest.fn();
  2. mockFn();
  3. expect(mockFn).toHaveBeenCalled();
  4. // With a mock implementation:
  5. const returnsTrue = jest.fn(() => true);
  6. console.log(returnsTrue()); // true;

jest.isMockFunction(fn)

Determines if the given function is a mocked function.

jest.spyOn(object, methodName)

Creates a mock function similar to jest.fn but also tracks calls to object[methodName]. Returns a Jest mock function.

Note: By default, jest.spyOn also calls the spied method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use jest.spyOn(object, methodName).mockImplementation(() => customImplementation) or object[methodName] = jest.fn(() => customImplementation);

示例:

  1. const video = {
  2. play() {
  3. return true;
  4. },
  5. };
  6. module.exports = video;

Example test:

  1. const video = require('./video');
  2. test('plays video', () => {
  3. const spy = jest.spyOn(video, 'play');
  4. const isPlaying = video.play();
  5. expect(spy).toHaveBeenCalled();
  6. expect(isPlaying).toBe(true);
  7. spy.mockRestore();
  8. });

jest.spyOn(object, methodName, accessType?)

Since Jest 22.1.0+, the jest.spyOn method takes an optional third argument of accessType that can be either 'get' or 'set', which proves to be useful when you want to spy on a getter or a setter, respectively.

示例:

  1. const video = {
  2. // it's a getter!
  3. get play() {
  4. return true;
  5. },
  6. };
  7. module.exports = video;
  8. const audio = {
  9. _volume: false,
  10. // it's a setter!
  11. set volume(value) {
  12. this._volume = value;
  13. },
  14. get volume() {
  15. return this._volume;
  16. },
  17. };
  18. module.exports = audio;

Example test:

  1. const video = require('./video');
  2. test('plays video', () => {
  3. const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get'
  4. const isPlaying = video.play;
  5. expect(spy).toHaveBeenCalled();
  6. expect(isPlaying).toBe(true);
  7. spy.mockRestore();
  8. });
  9. const audio = require('./audio');
  10. test('plays audio', () => {
  11. const spy = jest.spyOn(audio, 'volume', 'set'); // we pass 'set'
  12. audio.volume = 100;
  13. expect(spy).toHaveBeenCalled();
  14. expect(audio.volume).toBe(100);
  15. spy.mockRestore();
  16. });

jest.clearAllMocks()

Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function.

Returns the jest object for chaining.

jest.resetAllMocks()

Resets the state of all mocks. Equivalent to calling .mockReset() on every mocked function.

Returns the jest object for chaining.

jest.restoreAllMocks()

Restores all mocks back to their original value. Equivalent to calling .mockRestore() on every mocked function. Beware that jest.restoreAllMocks() only works when the mock was created with jest.spyOn; other mocks will require you to manually restore them.

Mock timers

jest.useFakeTimers()

Instructs Jest to use fake versions of the standard timer functions (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, setImmediate and clearImmediate).

Returns the jest object for chaining.

jest.useRealTimers()

Instructs Jest to use the real versions of the standard timer functions.

Returns the jest object for chaining.

jest.runAllTicks()

Exhausts the micro-task queue (usually interfaced in node via process.nextTick).

When this API is called, all pending micro-tasks that have been queued via process.nextTick will be executed. Additionally, if those micro-tasks themselves schedule new micro-tasks, those will be continually exhausted until there are no more micro-tasks remaining in the queue.

jest.runAllTimers()

Exhausts both the macro-task queue (i.e., all tasks queued by setTimeout(), setInterval(), and setImmediate()) and the micro-task queue (usually interfaced in node via process.nextTick).

When this API is called, all pending macro-tasks and micro-tasks will be executed. If those tasks themselves schedule new tasks, those will be continually exhausted until there are no more tasks remaining in the queue.

This is often useful for synchronously executing setTimeouts during a test in order to synchronously assert about some behavior that would only happen after the setTimeout() or setInterval() callbacks executed. See the Timer mocks doc for more information.

jest.runAllImmediates()

Exhausts all tasks queued by setImmediate().

jest.advanceTimersByTime(msToRun)

renamed in Jest 22.0.0+

Also under the alias: .runTimersToTime()

Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()).

When this API is called, all timers are advanced by msToRun milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed within this time frame will be executed. Additionally if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue, that should be run within msToRun milliseconds.

jest.runOnlyPendingTimers()

Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call.

This is useful for scenarios such as one where the module being tested schedules a setTimeout() whose callback schedules another setTimeout() recursively (meaning the scheduling never stops). In these scenarios, it's useful to be able to run forward in time by a single step at a time.

jest.advanceTimersToNextTimer(steps)

Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run.

Optionally, you can provide steps, so it will run steps amount of next timeouts/intervals.

jest.clearAllTimers()

Removes any pending timers from the timer system.

This means, if any timers have been scheduled (but have not yet executed), they will be cleared and will never have the opportunity to execute in the future.

jest.getTimerCount()

Returns the number of fake timers still left to run.

Misc

jest.setTimeout(timeout)

Set the default timeout interval for tests and before/after hooks in milliseconds.

Note: The default timeout interval is 5 seconds if this method is not called.

Note: If you want to set the timeout for all test files, a good place to do this is in setupFilesAfterEnv.

示例:

  1. jest.setTimeout(1000); // 1 second

jest.retryTimes()

Runs failed tests n-times until they pass or until the max number of retries is exhausted. This only works with jest-circus!

Example in a test:

  1. jest.retryTimes(3);
  2. test('will fail', () => {
  3. expect(true).toBe(false);
  4. });

Returns the jest object for chaining.