Jest 对象

jest 对象会自动注入到每个测试文件中, jest 对象上的方法帮助你创建模拟并让你控制 Jest 的整体行为。 也可以通过 import { jest } from '@jest/globals' 手动进行引入。

Jest 对象 - 图1info

The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:

  1. import {expect, jest, test} from '@jest/globals';

Consult the Getting Started guide for details on how to setup Jest with TypeScript.

方法


Mock Modules

jest.disableAutomock()

Disables automatic mocking in the module loader.

Jest 对象 - 图2info

Automatic mocking should be enabled via automock configuration option for this method to have any effect. Also see documentation of the configuration option for more details.

  • JavaScript
  • TypeScript
  1. /** @type {import('jest').Config} */
  2. const config = {
  3. automock: true,
  4. };
  5. module.exports = config;
  1. import type {Config} from 'jest';
  2. const config: Config = {
  3. automock: true,
  4. };
  5. export default config;

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

utils.js

  1. export default {
  2. authorize: () => {
  3. return 'token';
  4. },
  5. };

__tests__/disableAutomocking.js

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

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. 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, lodash, array utilities, etc) and entire libraries like React.js.

返回 jest 对象进行链式操作。

Jest 对象 - 图3tip

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.

Jest 对象 - 图4info

For more details on automatic mocking see documentation of automock configuration option.

示例:

utils.js

  1. export default {
  2. authorize: () => {
  3. return 'token';
  4. },
  5. isAuthorized: secret => secret === 'wizard',
  6. };

__tests__/enableAutomocking.js

  1. jest.enableAutomock();
  2. import utils from '../utils';
  3. test('original implementation', () => {
  4. // now we have the mocked implementation,
  5. expect(utils.authorize._isMockFunction).toBeTruthy();
  6. expect(utils.isAuthorized._isMockFunction).toBeTruthy();
  7. });

返回 jest 对象进行链式操作。

Jest 对象 - 图5tip

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.createMockFromModule(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:

  • JavaScript
  • TypeScript

utils.js

  1. module.exports = {
  2. authorize: () => {
  3. return 'token';
  4. },
  5. isAuthorized: secret => secret === 'wizard',
  6. };

__tests__/createMockFromModule.test.js

  1. const utils = jest.createMockFromModule('../utils');
  2. utils.isAuthorized = jest.fn(secret => secret === 'not wizard');
  3. test('implementation created by jest.createMockFromModule', () => {
  4. expect(jest.isMockFunction(utils.authorize)).toBe(true);
  5. expect(utils.isAuthorized('not wizard')).toBe(true);
  6. });

utils.ts

  1. export const utils = {
  2. authorize: () => {
  3. return 'token';
  4. },
  5. isAuthorized: (secret: string) => secret === 'wizard',
  6. };

__tests__/createMockFromModule.test.ts

  1. const {utils} =
  2. jest.createMockFromModule<typeof import('../utils')>('../utils');
  3. utils.isAuthorized = jest.fn((secret: string) => secret === 'not wizard');
  4. test('implementation created by jest.createMockFromModule', () => {
  5. expect(jest.isMockFunction(utils.authorize)).toBe(true);
  6. expect(utils.isAuthorized('not wizard')).toBe(true);
  7. });

This is how createMockFromModule will mock the following data types:

函数

创建一个新的 模拟函数。 The new function has no formal parameters and when called will return undefined. This functionality also applies to async functions.

Creates a new class. Creates a 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. Creates a new deeply cloned object. The object keys are maintained and their values are mocked.

数组

Creates a new empty array, ignoring the original.

基本类型

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

示例:

example.js

  1. module.exports = {
  2. function: function square(a, b) {
  3. return a * b;
  4. },
  5. asyncFunction: async function asyncSquare(a, b) {
  6. const result = (await a) * b;
  7. return result;
  8. },
  9. class: new (class Bar {
  10. constructor() {
  11. this.array = [1, 2, 3];
  12. }
  13. foo() {}
  14. })(),
  15. object: {
  16. baz: 'foo',
  17. bar: {
  18. fiz: 1,
  19. buzz: [1, 2, 3],
  20. },
  21. },
  22. array: [1, 2, 3],
  23. number: 123,
  24. string: 'baz',
  25. boolean: true,
  26. symbol: Symbol.for('a.b.c'),
  27. };

__tests__/example.test.js

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

jest.mock(moduleName, factory, options)

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

banana.js

  1. module.exports = () => 'banana';

__tests__/test.js

  1. jest.mock('../banana');
  2. const banana = require('../banana'); // banana will be explicitly mocked.
  3. 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:

  • JavaScript
  • TypeScript
  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';
  7. const moduleName = require('../moduleName');
  8. moduleName(); // Will return '42';
  1. // The optional type argument provides typings for the module factory
  2. jest.mock<typeof import('../moduleName')>('../moduleName', () => {
  3. return jest.fn(() => 42);
  4. });
  5. // This runs the function specified as second argument to `jest.mock`.
  6. const moduleName = require('../moduleName');
  7. 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: 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. );
  11. */
  12. },
  13. {virtual: true},
  14. );

Jest 对象 - 图6caution

Importing a module in a setup file (as specified by setupFilesAfterEnv) 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. Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module.

返回 jest 对象进行链式操作。

Jest 对象 - 图7tip

Writing tests in TypeScript? Use the jest.Mocked utility type or the jest.mocked() helper method to have your mocked modules typed.

jest.Mocked<Source>

See TypeScript Usage chapter of Mock Functions page for documentation.

jest.mocked(source, options?)

See TypeScript Usage chapter of Mock Functions page for documentation.

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).

返回 jest 对象进行链式操作。

jest.deepUnmock(moduleName)

Indicates that the module system should never return a mocked version of the specified module and its dependencies.

返回 jest 对象进行链式操作。

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:

  • JavaScript
  • TypeScript
  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()).toBe(1);
  10. });
  11. test('moduleName 2', () => {
  12. jest.doMock('../moduleName', () => {
  13. return jest.fn(() => 2);
  14. });
  15. const moduleName = require('../moduleName');
  16. expect(moduleName()).toBe(2);
  17. });
  1. beforeEach(() => {
  2. jest.resetModules();
  3. });
  4. test('moduleName 1', () => {
  5. // The optional type argument provides typings for the module factory
  6. jest.doMock<typeof import('../moduleName')>('../moduleName', () => {
  7. return jest.fn(() => 1);
  8. });
  9. const moduleName = require('../moduleName');
  10. expect(moduleName()).toBe(1);
  11. });
  12. test('moduleName 2', () => {
  13. jest.doMock<typeof import('../moduleName')>('../moduleName', () => {
  14. return jest.fn(() => 2);
  15. });
  16. const moduleName = require('../moduleName');
  17. expect(moduleName()).toBe(2);
  18. });

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

  • 必须指定 __esModule: true 属性(见 jest.mock() API以获取更多信息)
  • 静态的 ES6 模块导入语句将会被置于文件顶部,所以应该使用 import() 进行模块的动态导入
  • 最后,需要一个支持动态导入的环境。 请查看 使用 Babel 进行初始设置。 然后添加 babel-plugin-dynamic-import-node 插件或者其他有相同功能的插件来确保 Babel 开启了在 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).toBe('default1');
  14. expect(moduleName.foo).toBe('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).toBe('default2');
  27. expect(moduleName.foo).toBe('foo2');
  28. });
  29. });

返回 jest 对象进行链式操作。

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. Use this method if you want to explicitly avoid this behavior.

返回 jest 对象进行链式操作。

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. 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. 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.

返回 jest 对象进行链式操作。

Jest 对象 - 图8info

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.

  • JavaScript
  • TypeScript
  1. jest.mock('../myModule', () => {
  2. // Require the original module to not be mocked...
  3. const originalModule = jest.requireActual('../myModule');
  4. return {
  5. __esModule: true, // Use it when dealing with esModules
  6. ...originalModule,
  7. getRandom: jest.fn(() => 10),
  8. };
  9. });
  10. const getRandom = require('../myModule').getRandom;
  11. getRandom(); // Always returns 10
  1. jest.mock('../myModule', () => {
  2. // Require the original module to not be mocked...
  3. const originalModule =
  4. jest.requireActual<typeof import('../myModule')>('../myModule');
  5. return {
  6. __esModule: true, // Use it when dealing with esModules
  7. ...originalModule,
  8. getRandom: jest.fn(() => 10),
  9. };
  10. });
  11. const getRandom = require('../myModule').getRandom;
  12. 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. 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. });
  11. });

返回 jest 对象进行链式操作。

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. 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');

jest.isolateModulesAsync(fn)

jest.isolateModulesAsync() is the equivalent of jest.isolateModules(), but for async callbacks. The caller is expected to await the completion of isolateModulesAsync.

  1. let myModule;
  2. await jest.isolateModulesAsync(async () => {
  3. myModule = await import('myModule');
  4. // do async stuff here
  5. });
  6. const otherCopyOfMyModule = await import('myModule');

模拟函数

jest.fn(implementation?)

Returns a new, unused mock function. Optionally takes a mock implementation. 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 对象 - 图9tip

See the Mock Functions page for details on TypeScript usage.

jest.isMockFunction(fn)

Determines if the given function is a mocked function.

jest.replaceProperty(object, propertyKey, value)

Replace object[propertyKey] with a value. The property must already exist on the object. The same property might be replaced multiple times. Returns a Jest replaced property.

Jest 对象 - 图10note

To mock properties that are defined as getters or setters, use jest.spyOn(object, methodName, accessType) instead. To mock functions, use jest.spyOn(object, methodName) instead.

Jest 对象 - 图11tip

All properties replaced with jest.replaceProperty could be restored to the original value by calling jest.restoreAllMocks on afterEach method.

示例:

  1. const utils = {
  2. isLocalhost() {
  3. return process.env.HOSTNAME === 'localhost';
  4. },
  5. };
  6. module.exports = utils;

Example test:

  1. const utils = require('./utils');
  2. afterEach(() => {
  3. // restore replaced property
  4. jest.restoreAllMocks();
  5. });
  6. test('isLocalhost returns true when HOSTNAME is localhost', () => {
  7. jest.replaceProperty(process, 'env', {HOSTNAME: 'localhost'});
  8. expect(utils.isLocalhost()).toBe(true);
  9. });
  10. test('isLocalhost returns false when HOSTNAME is not localhost', () => {
  11. jest.replaceProperty(process, 'env', {HOSTNAME: 'not-localhost'});
  12. expect(utils.isLocalhost()).toBe(false);
  13. });

jest.spyOn(object, methodName)

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

Jest 对象 - 图12note

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 jest.replaceProperty(object, methodName, jest.fn(() => customImplementation));

Jest 对象 - 图13tip

Since jest.spyOn is a mock, you could restore the initial state by calling jest.restoreAllMocks in the body of the callback passed to the afterEach hook.

示例:

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

Example test:

  1. const video = require('./video');
  2. afterEach(() => {
  3. // restore the spy created with spyOn
  4. jest.restoreAllMocks();
  5. });
  6. test('plays video', () => {
  7. const spy = jest.spyOn(video, 'play');
  8. const isPlaying = video.play();
  9. expect(spy).toHaveBeenCalled();
  10. expect(isPlaying).toBe(true);
  11. });

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. const video = {
  4. // it's a getter!
  5. get play() {
  6. return true;
  7. },
  8. };
  9. module.exports = video;
  10. const audio = {
  11. _volume: false,
  12. // it's a setter!
  13. set volume(value) {
  14. this._volume = value;
  15. },
  16. get volume() {
  17. return this._volume;
  18. },
  19. };
  20. module.exports = audio;
  21. set volume(value) {
  22. this._volume = value;
  23. },
  24. get volume() {
  25. return this._volume;
  26. },
  27. };
  28. module.exports = audio;

Example test:

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

jest.Replaced<Source>

See TypeScript Usage chapter of Mock Functions page for documentation.

jest.Spied<Source>

See TypeScript Usage chapter of Mock Functions page for documentation.

jest.clearAllMocks()

清除所有模拟的属性: mock.calls, mock.instances, mock.contextmock.results 。 Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function.

返回 jest 对象进行链式操作。

jest.resetAllMocks()

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

返回 jest 对象进行链式操作。

jest.restoreAllMocks()

Restores all mocks and replaced properties back to their original value. Equivalent to calling .mockRestore() on every mocked function and .restore() on every replaced property. Beware that jest.restoreAllMocks() only works for mocks created with jest.spyOn() and properties replaced with jest.replaceProperty(); other mocks will require you to manually restore them.

假的定时器

jest.useFakeTimers(fakeTimersConfig?)

指定 Jest 使用假的全局日期、性能、时间和定时器 API。 假定时器实现由 @sinonjs/fake-timaters 支持。

假定时器会替换 Date, performance.now(), queueMicrotask(), setImmediate(), clearImmediate(), setInterval(), clearInterval(), setTimeout(), clearTimeout() 的实现从而获得假时间。

在 Node 环境下的 process.hrtime, process.nextTick() 和 JSDOM 环境下的 requestAnimationFrame(), cancelAnimationFrame(), requestIdleCallback(), cancelIdleCallback() 同样会被替换。

配置选项

  1. type FakeableAPI =
  2. | 'Date'
  3. | 'hrtime'
  4. | 'nextTick'
  5. | 'performance'
  6. | 'queueMicrotask'
  7. | 'requestAnimationFrame'
  8. | 'cancelAnimationFrame'
  9. | 'requestIdleCallback'
  10. | 'cancelIdleCallback'
  11. | 'setImmediate'
  12. | 'clearImmediate'
  13. | 'setInterval'
  14. | 'clearInterval'
  15. | 'setTimeout'
  16. | 'clearTimeout';
  17. type FakeTimersConfig = {
  18. /**
  19. * 如果设置为 true,所有定时器每隔20ms会提前20ms
  20. * 设置数字可以提供一个自定义的时间间隔
  21. * 默认为 false
  22. */
  23. advanceTimers?: boolean | number;
  24. /**
  25. * 传入不该被替换的API列表 默认是 [] 代表全部的API都被会替换
  26. */
  27. doNotFake?: Array<FakeableAPI>;
  28. /**
  29. * 使用原有的定时器实现而不是`@sinonjs/fake-timers`提供的
  30. * 默认为 false
  31. */
  32. legacyFakeTimers?: boolean;
  33. /** 设置假定时器的当前系统时间 默认值是 `Date.now ()`。 */
  34. now?: number | Date;
  35. /**
  36. * 调用 `jest.runAllTimers()`.时运行的定时器最大数量
  37. * 默认值是 `100_000` 计时器。
  38. */
  39. timerLimit?: number;
  40. };

调用 jest.useFakeTimers() 将在所有测试中使用假定时器,直到调用jest.useRealTimers()恢复使用原定时器

可以在任何地方调用 jest.useFakeTimers()jest.useRealTimers()(如顶层,it内部等)。 请记住,这是一个 全局操作 ,并将影响到同一文件中的其他测试。 在同一测试文件内再次调用 jest.useFakeTimers() 会重置内部状态(如计时器计数),并使用提供的选项重新载入假定时器替换原生的API。

  1. test('advance the timers automatically', () => {
  2. jest.useFakeTimers({advanceTimers: true});
  3. // ...
  4. });
  5. test('do not advance the timers and do not fake `performance`', () => {
  6. jest.useFakeTimers({doNotFake: ['performance']});
  7. // ...
  8. });
  9. test('uninstall fake timers for the rest of tests in the file', () => {
  10. jest.useRealTimers();
  11. // ...
  12. });

旧版本的假定时器

出于某些原因,你可能不得不使用旧版本的假定时器。 可以像这样启用 (不支持其他选项):

  1. jest.useFakeTimers({
  2. legacyFakeTimers: true,
  3. });

旧版本的假定时器使用 Jest mock functions 替换掉 setImmediate(), clearImmediate(), setInterval(), clearInterval(), setTimeout(), clearTimeout(), 以及 Node 环境下的 process.nextTick() ,JSDOM 环境下的 requestAnimationFrame(), cancelAnimationFrame()

:::

返回 jest 对象进行链式操作。

jest.useRealTimers()

指定 Jest 使用真实的全局日期、性能、时间和定时器 API。 比如,你可以在 afterEach 里调用 jest.useRealTimers() 实现每一次测试结束后恢复真实的定时器。

  1. afterEach(() => {
  2. jest.useRealTimers();
  3. });
  4. test('do something with fake timers', () => {
  5. jest.useFakeTimers();
  6. // ...
  7. });
  8. test('do something with real timers', () => {
  9. // ...
  10. });
  11. });
  12. test('do something with real timers', () => {
  13. // ...
  14. });

返回 jest 对象进行链式操作。

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. 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. 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. See the Timer mocks doc for more information.

jest.runAllImmediates()

Exhausts all tasks queued by setImmediate().

Jest 对象 - 图14info

此功能仅在使用旧的假定时器实现时才可用。

jest.advanceTimersByTime(msToRun)

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

通过调用msToRun这个 API时, 所有计时器都将以毫秒增长。 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. 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. 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. 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.

jest.now()

Returns the time in ms of the current clock. This is equivalent to Date.now() if real timers are in use, or if Date is mocked. In other cases (such as legacy timers) it may be useful for implementing custom mocks of Date.now(), performance.now(), etc.

jest.setSystemTime(now?: number | Date)

Set the current system time used by fake timers. Simulates a user changing the system clock while your program is running. Set the current system time used by fake timers. Simulates a user changing the system clock while your program is running. It affects the current time but it does not in itself cause e.g. timers to fire; they will fire exactly as they would have done without the call to jest.setSystemTime().

Jest 对象 - 图15info

此功能在使用旧的假定时器时不可用。

jest.getRealSystemTime()

When mocking time, Date.now() will also be mocked. If you for some reason need access to the real current time, you can invoke this function. If you for some reason need access to the real current time, you can invoke this function.

Jest 对象 - 图16info

此功能在使用旧的假定时器时不可用。

Misc

jest.getSeed()

Every time Jest runs a seed value is randomly generated which you could use in a pseudorandom number generator or anywhere else.

Jest 对象 - 图17tip

Use the --showSeed flag to print the seed in the test report summary. To manually set the value of the seed use --seed= CLI argument.

jest.isEnvironmentTornDown()

Returns true if test environment has been torn down.

jest.retryTimes(numRetries, options)

Runs failed tests n-times until they pass or until the max number of retries is exhausted. options 是可选参数 This only works with the default jest-circus runner! This must live at the top-level of a test file or in a describe block. Retries will not work if jest.retryTimes() is called in a beforeEach or a test block.

Example in a test:

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

如果 LogorsBEforestry 选项启用, Jest 将导致测试失败的错误打印到控制台,方便查看测试重试的原因。

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

返回 jest 对象进行链式操作。

jest.setTimeout(timeout)

Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. This only affects the test file from which this function is called. The default timeout interval is 5 seconds if this method is not called.

示例:

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

Jest 对象 - 图18tip

To set timeout intervals on different tests in the same file, use the timeout option on each individual test.

If you want to set the timeout for all test files, use testTimeout configuration option.