Skip to main content
Version: 29.7

Jest 对象

jest 对象自动位于每个测试文件的范围内。jest 对象中的方法有助于创建模拟并让你控制 Jest 的整体行为。也可以通过 via import {jest} from '@jest/globals' 显式导入。

¥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. It can also be imported explicitly by via import {jest} from '@jest/globals'.

信息

仅当你显式导入 Jest API 时,此页面中的 TypeScript 示例才会按照文档说明的方式工作:

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

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

有关如何使用 TypeScript 设置 Jest 的详细信息,请参阅 入门 指南。

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

方法

¥Methods


模拟模块

¥Mock Modules

jest.disableAutomock()

禁用模块加载器中的自动模拟。

¥Disables automatic mocking in the module loader.

信息

应通过 automock 配置选项启用自动模拟,此方法才能发挥作用。另请参阅配置选项的文档以了解更多详细信息。

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

/** @type {import('jest').Config} */
const config = {
automock: true,
};

module.exports = config;

调用 disableAutomock() 后,所有 require() 将返回每个模块的真实版本(而不是模拟版本)。

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

utils.js
export default {
authorize: () => {
return 'token';
},
};
__tests__/disableAutomocking.js
import utils from '../utils';

jest.disableAutomock();

test('original implementation', () => {
// now we have the original implementation,
// even if we set the automocking in a jest configuration
expect(utils.authorize()).toBe('token');
});

当你想要模拟的依赖数量远远少于你不模拟的依赖数量的场景时,这通常很有用。例如,如果你正在为一个使用大量依赖的模块编写测试,这些依赖可以合理地分类为模块的 "实现细节",那么你可能不想模拟它们。

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

可能被视为 "实现细节" 的依赖示例包括从语言内置函数(例如 Array.prototype 方法)到高度常见的实用程序方法(例如 underscorelodash、数组实用程序等)以及整个库(例如 React.js)。

¥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 对象。

¥Returns the jest object for chaining.

提示

使用 babel-jest 时,对 disableAutomock() 的调用将自动提升到代码块的顶部。如果你想明确避免此行为,请使用 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.

信息

有关自动模拟的更多详细信息,请参阅 automock 配置选项的文档。

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

示例:

¥Example:

utils.js
export default {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
__tests__/enableAutomocking.js
jest.enableAutomock();

import utils from '../utils';

test('original implementation', () => {
// now we have the mocked implementation,
expect(utils.authorize._isMockFunction).toBeTruthy();
expect(utils.isAuthorized._isMockFunction).toBeTruthy();
});

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

提示

使用 babel-jest 时,对 enableAutomock 的调用将自动提升到代码块的顶部。如果你想明确避免此行为,请使用 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.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:

utils.js
module.exports = {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
__tests__/createMockFromModule.test.js
const utils = jest.createMockFromModule('../utils');

utils.isAuthorized = jest.fn(secret => secret === 'not wizard');

test('implementation created by jest.createMockFromModule', () => {
expect(jest.isMockFunction(utils.authorize)).toBe(true);
expect(utils.isAuthorized('not wizard')).toBe(true);
});

这就是 createMockFromModule 将模拟以下数据类型的方式:

¥This is how createMockFromModule will mock the following data types:

Function

创建一个新的 模拟函数。新函数没有形式参数,调用时将返回 undefined。此功能也适用于 async 功能。

¥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 a new class. The interface of the original class is maintained, all of the class member functions and properties will be mocked.

Object

创建一个新的深度克隆对象。维护对象键并模拟它们的值。

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

Array

创建一个新的空数组,忽略原始数组。

¥Creates a new empty array, ignoring the original.

Primitives

创建一个与原始属性具有相同原始值的新属性。

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

示例:

¥Example:

example.js
module.exports = {
function: function square(a, b) {
return a * b;
},
asyncFunction: async function asyncSquare(a, b) {
const result = (await a) * b;
return result;
},
class: new (class Bar {
constructor() {
this.array = [1, 2, 3];
}
foo() {}
})(),
object: {
baz: 'foo',
bar: {
fiz: 1,
buzz: [1, 2, 3],
},
},
array: [1, 2, 3],
number: 123,
string: 'baz',
boolean: true,
symbol: Symbol.for('a.b.c'),
};
__tests__/example.test.js
const example = jest.createMockFromModule('../example');

test('should run example code', () => {
// creates a new mocked function with no formal arguments.
expect(example.function.name).toBe('square');
expect(example.function).toHaveLength(0);

// async functions get the same treatment as standard synchronous functions.
expect(example.asyncFunction.name).toBe('asyncSquare');
expect(example.asyncFunction).toHaveLength(0);

// creates a new class with the same interface, member functions and properties are mocked.
expect(example.class.constructor.name).toBe('Bar');
expect(example.class.foo.name).toBe('foo');
expect(example.class.array).toHaveLength(0);

// creates a deeply cloned version of the original object.
expect(example.object).toEqual({
baz: 'foo',
bar: {
fiz: 1,
buzz: [],
},
});

// creates a new empty array, ignoring the original array.
expect(example.array).toHaveLength(0);

// creates a new property with the same primitive value as the original property.
expect(example.number).toBe(123);
expect(example.string).toBe('baz');
expect(example.boolean).toBe(true);
expect(example.symbol).toEqual(Symbol.for('a.b.c'));
});

jest.mock(moduleName, factory, options)

在需要时使用自动模拟版本来模拟模块。factoryoptions 是可选的。例如:

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

banana.js
module.exports = () => 'banana';
__tests__/test.js
jest.mock('../banana');

const banana = require('../banana'); // banana will be explicitly mocked.

banana(); // will return 'undefined' because the function is auto-mocked.

第二个参数可用于指定正在运行的显式模块工厂,而不是使用 Jest 的自动模拟功能:

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

jest.mock('../moduleName', () => {
return jest.fn(() => 42);
});

// This runs the function specified as second argument to `jest.mock`.
const moduleName = require('../moduleName');
moduleName(); // Will return '42';

当对具有默认导出的 ES6 模块使用 factory 参数时,需要指定 __esModule: true 属性。该属性通常由 Babel / TypeScript 生成,但这里需要手动设置。当导入默认导出时,它是从导出对象导入名为 default 的属性的指令:

¥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:

import moduleName, {foo} from '../moduleName';

jest.mock('../moduleName', () => {
return {
__esModule: true,
default: jest.fn(() => 42),
foo: jest.fn(() => 43),
};
});

moduleName(); // Will return 42
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:

jest.mock(
'../moduleName',
() => {
/*

* Custom implementation of a module that doesn't exist in JS,

* like a generated module or a native module in react-native.
*/
},
{virtual: true},
);
提醒

在设置文件中导入模块(由 setupFilesAfterEnv 指定)将防止模拟相关模块及其导入的所有模块。

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

使用 jest.mock 模拟的模块仅针对调用 jest.mock 的文件进行模拟。导入该模块的另一个文件将获得原始实现,即使它在模拟该模块的测试文件之后运行。

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

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

提示

用 TypeScript 编写测试?使用 jest.Mocked 工具类型或 jest.mocked() 辅助方法来键入模拟模块。

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

有关文档,请参阅模拟函数页面的 TypeScript 用法 章。

¥See TypeScript Usage chapter of Mock Functions page for documentation.

jest.mocked(source, options?)

有关文档,请参阅模拟函数页面的 TypeScript 用法 章。

¥See TypeScript Usage chapter of Mock Functions page for documentation.

jest.unmock(moduleName)

指示模块系统永远不应该从 require() 返回指定模块的模拟版本(例如,它应该始终返回真实模块)。

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

此 API 最常见的用途是指定给定测试要测试的模块(因此不希望自动模拟)。

¥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 对象。

¥Returns the jest object for chaining.

jest.deepUnmock(moduleName)

指示模块系统永远不应返回指定模块及其依赖的模拟版本。

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

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

jest.doMock(moduleName, factory, options)

使用 babel-jest 时,对 mock 的调用将自动提升到代码块的顶部。如果你想明确避免此行为,请使用此方法。

¥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:

beforeEach(() => {
jest.resetModules();
});

test('moduleName 1', () => {
jest.doMock('../moduleName', () => {
return jest.fn(() => 1);
});
const moduleName = require('../moduleName');
expect(moduleName()).toBe(1);
});

test('moduleName 2', () => {
jest.doMock('../moduleName', () => {
return jest.fn(() => 2);
});
const moduleName = require('../moduleName');
expect(moduleName()).toBe(2);
});

jest.doMock() 与 ES6 导入一起使用需要额外的步骤。如果你不想在测试中使用 require,请按照以下步骤操作:

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

  • 我们必须指定 __esModule: true 属性(有关更多信息,请参阅 jest.mock() API)。

    ¥We have to specify the __esModule: true property (see the jest.mock() API for more information).

  • 静态 ES6 模块导入被提升到文件顶部,因此我们必须使用 import() 动态导入它们。

    ¥Static ES6 module imports are hoisted to the top of the file, so instead we have to import them dynamically using import().

  • 最后,我们需要一个支持动态导入的环境。请参阅 使用 Babel 了解初始设置。然后将插件 babel-plugin-dynamic-import-node 或等效插件添加到 Babel 配置中,以在 Node.js 中启用动态导入。

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

beforeEach(() => {
jest.resetModules();
});

test('moduleName 1', () => {
jest.doMock('../moduleName', () => {
return {
__esModule: true,
default: 'default1',
foo: 'foo1',
};
});
return import('../moduleName').then(moduleName => {
expect(moduleName.default).toBe('default1');
expect(moduleName.foo).toBe('foo1');
});
});

test('moduleName 2', () => {
jest.doMock('../moduleName', () => {
return {
__esModule: true,
default: 'default2',
foo: 'foo2',
};
});
return import('../moduleName').then(moduleName => {
expect(moduleName.default).toBe('default2');
expect(moduleName.foo).toBe('foo2');
});
});

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

jest.dontMock(moduleName)

使用 babel-jest 时,对 unmock 的调用将自动提升到代码块的顶部。如果你想明确避免此行为,请使用此方法。

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

返回用于链接的 jest 对象。

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

在这些罕见的情况下,你可以使用此 API 手动填充模块系统的模拟模块注册表中的插槽。

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

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

信息

建议使用 jest.mock() 代替。jest.mock API 的第二个参数是模块工厂,而不是预期导出的模块对象。

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

jest.mock('../myModule', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('../myModule');

return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
getRandom: jest.fn(() => 10),
};
});

const getRandom = require('../myModule').getRandom;

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.

示例:

¥Example:

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

测试中的示例:

¥Example in a test:

beforeEach(() => {
jest.resetModules();
});

test('works', () => {
const sum = require('../sum');
});

test('works too', () => {
const sum = require('../sum');
// sum is a different copy of the sum module from the previous test.
});

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

jest.isolateModules(fn)

jest.isolateModules(fn)jest.resetModules() 更进一步,为回调函数中加载的模块创建了一个沙箱注册表。这对于隔离每个测试的特定模块很有用,这样本地模块状态就不会在测试之间发生冲突。

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

let myModule;
jest.isolateModules(() => {
myModule = require('myModule');
});

const otherCopyOfMyModule = require('myModule');

jest.isolateModulesAsync(fn)

jest.isolateModulesAsync()jest.isolateModules() 等效,但用于异步回调。调用者预计 await 完成 isolateModulesAsync

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

let myModule;
await jest.isolateModulesAsync(async () => {
myModule = await import('myModule');
// do async stuff here
});

const otherCopyOfMyModule = await import('myModule');

模拟函数

¥Mock Functions

jest.fn(implementation?)

返回一个新的、未使用的 模拟函数。可以选择进行模拟实现。

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

const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();

// With a mock implementation:
const returnsTrue = jest.fn(() => true);
console.log(returnsTrue()); // true;
提示

有关 TypeScript 使用的详细信息,请参阅 模拟函数 页面。

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

object[propertyKey] 替换为 value。该属性必须已存在于对象上。同一属性可能会被替换多次。返回 Jest 更换属性

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

注意

要模拟定义为 getter 或 setter 的属性,请改用 jest.spyOn(object, methodName, accessType)。要模拟函数,请改用 jest.spyOn(object, methodName)

¥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.replaceProperty 替换的属性都可以通过在 afterEach 方法上调用 jest.restoreAllMocks 来恢复到原始值。

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

示例:

¥Example:

const utils = {
isLocalhost() {
return process.env.HOSTNAME === 'localhost';
},
};

module.exports = utils;

测试示例:

¥Example test:

const utils = require('./utils');

afterEach(() => {
// restore replaced property
jest.restoreAllMocks();
});

test('isLocalhost returns true when HOSTNAME is localhost', () => {
jest.replaceProperty(process, 'env', {HOSTNAME: 'localhost'});
expect(utils.isLocalhost()).toBe(true);
});

test('isLocalhost returns false when HOSTNAME is not localhost', () => {
jest.replaceProperty(process, 'env', {HOSTNAME: 'not-localhost'});
expect(utils.isLocalhost()).toBe(false);
});

jest.spyOn(object, methodName)

创建一个类似于 jest.fn 的模拟函数,但也跟踪对 object[methodName] 的调用。返回 Jest 模拟函数

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

注意

默认情况下,jest.spyOn 也会调用 sied 方法。这与大多数其他测试库的行为不同。如果要覆盖原来的函数,可以使用 jest.spyOn(object, methodName).mockImplementation(() => customImplementation)object[methodName] = jest.fn(() => customImplementation)

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

提示

由于 jest.spyOn 是模拟,因此你可以通过在传递给 afterEach 钩子的回调正文中调用 jest.restoreAllMocks 来恢复初始状态。

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

示例:

¥Example:

const video = {
play() {
return true;
},
};

module.exports = video;

测试示例:

¥Example test:

const video = require('./video');

afterEach(() => {
// restore the spy created with spyOn
jest.restoreAllMocks();
});

test('plays video', () => {
const spy = jest.spyOn(video, 'play');
const isPlaying = video.play();

expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(true);
});

jest.spyOn(object, methodName, accessType?)

从 Jest 22.1.0+ 开始,jest.spyOn 方法采用 accessType 的可选第三个参数,可以是 'get''set',当你想要分别监视 getter 或 setter 时,这被证明是有用的。

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

示例:

¥Example:

const video = {
// it's a getter!
get play() {
return true;
},
};

module.exports = video;

const audio = {
_volume: false,
// it's a setter!
set volume(value) {
this._volume = value;
},
get volume() {
return this._volume;
},
};

module.exports = audio;

测试示例:

¥Example test:

const audio = require('./audio');
const video = require('./video');

afterEach(() => {
// restore the spy created with spyOn
jest.restoreAllMocks();
});

test('plays video', () => {
const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get'
const isPlaying = video.play;

expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(true);
});

test('plays audio', () => {
const spy = jest.spyOn(audio, 'volume', 'set'); // we pass 'set'
audio.volume = 100;

expect(spy).toHaveBeenCalled();
expect(audio.volume).toBe(100);
});

jest.Replaced<Source>

有关文档,请参阅模拟函数页面的 TypeScript 用法 章。

¥See TypeScript Usage chapter of Mock Functions page for documentation.

jest.Spied<Source>

有关文档,请参阅模拟函数页面的 TypeScript 用法 章。

¥See TypeScript Usage chapter of Mock Functions page for documentation.

jest.clearAllMocks()

清除所有模拟的 mock.callsmock.instancesmock.contextsmock.results 属性。相当于在每个模拟函数上调用 .mockClear()

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

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

jest.resetAllMocks()

重置所有模拟的状态。相当于在每个模拟函数上调用 .mockReset()

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

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

jest.restoreAllMocks()

将所有模拟和替换的属性恢复为其原始值。相当于在每个模拟函数上调用 .mockRestore(),在每个替换属性上调用 .restore()。请注意,jest.restoreAllMocks() 仅适用于使用 jest.spyOn() 创建的模拟,并且属性替换为 jest.replaceProperty();其他模拟将需要你手动恢复它们。

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

假定时器

¥Fake Timers

jest.useFakeTimers(fakeTimersConfig?)

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

¥Instructs Jest to use fake versions of the global date, performance, time and timer APIs. Fake timers implementation is backed by @sinonjs/fake-timers.

假定时器将用从假时钟获取时间的实现来替换 Dateperformance.now()queueMicrotask()setImmediate()clearImmediate()setInterval()clearInterval()setTimeout()clearTimeout()

¥Fake timers will swap out Date, performance.now(), queueMicrotask(), setImmediate(), clearImmediate(), setInterval(), clearInterval(), setTimeout(), clearTimeout() with an implementation that gets its time from the fake clock.

在 Node 环境中 process.hrtimeprocess.nextTick() 和在 JSDOM 环境中 requestAnimationFrame()cancelAnimationFrame()requestIdleCallback()cancelIdleCallback() 也将被替换。

¥In Node environment process.hrtime, process.nextTick() and in JSDOM environment requestAnimationFrame(), cancelAnimationFrame(), requestIdleCallback(), cancelIdleCallback() will be replaced as well.

配置选项:

¥Configuration options:

type FakeableAPI =
| 'Date'
| 'hrtime'
| 'nextTick'
| 'performance'
| 'queueMicrotask'
| 'requestAnimationFrame'
| 'cancelAnimationFrame'
| 'requestIdleCallback'
| 'cancelIdleCallback'
| 'setImmediate'
| 'clearImmediate'
| 'setInterval'
| 'clearInterval'
| 'setTimeout'
| 'clearTimeout';

type FakeTimersConfig = {
/**

* If set to `true` all timers will be advanced automatically by 20 milliseconds

* every 20 milliseconds. A custom time delta may be provided by passing a number.

* The default is `false`.
*/
advanceTimers?: boolean | number;
/**

* List of names of APIs that should not be faked. The default is `[]`, meaning

* all APIs are faked.
*/
doNotFake?: Array<FakeableAPI>;
/**

* Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.

* The default is `false`.
*/
legacyFakeTimers?: boolean;
/** Sets current system time to be used by fake timers, in milliseconds. The default is `Date.now()`. */
now?: number | Date;
/**

* The maximum number of recursive timers that will be run when calling `jest.runAllTimers()`.

* The default is `100_000` timers.
*/
timerLimit?: number;
};

调用 jest.useFakeTimers() 将使用假定时器进行文件内的所有测试,直到使用 jest.useRealTimers() 恢复原始定时器。

¥Calling jest.useFakeTimers() will use fake timers for all tests within the file, until original timers are restored with jest.useRealTimers().

你可以从任何地方调用 jest.useFakeTimers()jest.useRealTimers():顶层、test 块内等。请记住,这是一个全局操作,将影响同一文件中的其他测试。在同一个测试文件中再次调用 jest.useFakeTimers() 将重置内部状态(例如计时器计数)并使用提供的选项重新安装假计时器:

¥You can call jest.useFakeTimers() or jest.useRealTimers() from anywhere: top level, inside an test block, etc. Keep in mind that this is a global operation and will affect other tests within the same file. Calling jest.useFakeTimers() once again in the same test file would reset the internal state (e.g. timer count) and reinstall fake timers using the provided options:

test('advance the timers automatically', () => {
jest.useFakeTimers({advanceTimers: true});
// ...
});

test('do not advance the timers and do not fake `performance`', () => {
jest.useFakeTimers({doNotFake: ['performance']});
// ...
});

test('uninstall fake timers for the rest of tests in the file', () => {
jest.useRealTimers();
// ...
});
旧版假定时器

由于某种原因,你可能必须使用假计时器的旧版实现。可以这样启用它(不支持其他选项):

¥For some reason you might have to use legacy implementation of fake timers. It can be enabled like this (additional options are not supported):

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

传统的假计时器将用 Jest 模拟函数 替换 setImmediate()clearImmediate()setInterval()clearInterval()setTimeout()clearTimeout()。在 Node 环境 process.nextTick() 和 JSDOM 环境 requestAnimationFrame() 中,cancelAnimationFrame() 也将被替换。

¥Legacy fake timers will swap out setImmediate(), clearImmediate(), setInterval(), clearInterval(), setTimeout(), clearTimeout() with Jest mock functions. In Node environment process.nextTick() and in JSDOM environment requestAnimationFrame(), cancelAnimationFrame() will be also replaced.

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

jest.useRealTimers()

指示 Jest 恢复全局日期、性能、时间和计时器 API 的原始实现。例如,你可以在 afterEach 钩子内调用 jest.useRealTimers() 以在每次测试后恢复计时器:

¥Instructs Jest to restore the original implementations of the global date, performance, time and timer APIs. For example, you may call jest.useRealTimers() inside afterEach hook to restore timers after each test:

afterEach(() => {
jest.useRealTimers();
});

test('do something with fake timers', () => {
jest.useFakeTimers();
// ...
});

test('do something with real timers', () => {
// ...
});

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

jest.runAllTicks()

耗尽微任务队列(通常通过 process.nextTick 在节点中连接)。

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

当调用此 API 时,所有通过 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()

耗尽宏任务队列(即按 setTimeout()setInterval()setImmediate() 排队的所有任务)和微任务队列(通常通过 process.nextTick 在节点中连接)。

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

当调用该 API 时,所有待处理的宏任务和微任务将被执行。如果这些任务本身调度新任务,这些任务将不断耗尽,直到队列中没有更多任务为止。

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

这对于在测试期间同步执行 setTimeouts 通常很有用,以便同步断言仅在执行 setTimeout()setInterval() 回调后才会发生的某些行为。有关更多信息,请参阅 计时器模拟 文档。

¥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.runAllTimersAsync()

异步相当于 jest.runAllTimers()。它允许在运行计时器之前执行任何预定的 promise 回调。

¥Asynchronous equivalent of jest.runAllTimers(). It allows any scheduled promise callbacks to execute before running the timers.

信息

当使用传统的假定时器实现时,此功能不可用。

¥This function is not available when using legacy fake timers implementation.

jest.runAllImmediates()

耗尽 setImmediate() 排队的所有任务。

¥Exhausts all tasks queued by setImmediate().

信息

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

¥This function is only available when using legacy fake timers implementation.

jest.advanceTimersByTime(msToRun)

仅执行宏任务队列(即按 setTimeout()setInterval()setImmediate() 排队的所有任务)。

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

调用此 API 时,所有计时器都会提前 msToRun 毫秒。所有已通过 setTimeout()setInterval() 排队并在此时间范围内执行的待处理 "macro-tasks" 都将被执行。此外,如果这些宏任务调度将在同一时间范围内执行的新宏任务,则这些宏任务将一直执行,直到队列中不再有宏任务剩余,该宏任务应在 msToRun 毫秒内运行。

¥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.advanceTimersByTimeAsync(msToRun)

异步相当于 jest.advanceTimersByTime(msToRun)。它允许在运行计时器之前执行任何预定的 promise 回调。

¥Asynchronous equivalent of jest.advanceTimersByTime(msToRun). It allows any scheduled promise callbacks to execute before running the timers.

信息

当使用传统的假定时器实现时,此功能不可用。

¥This function is not available when using legacy fake timers implementation.

jest.runOnlyPendingTimers()

仅执行当前待处理的宏任务(即仅执行到目前为止已按 setTimeout()setInterval() 排队的任务)。如果任何当前挂起的宏任务调度新的宏任务,则这些新任务将不会通过此调用执行。

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

这对于诸如被测试的模块调度 setTimeout() 的场景很有用,而 setTimeout() 的回调则递归地调度另一个 setTimeout()(意味着调度永远不会停止)。在这些场景中,能够一次向前运行一步非常有用。

¥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.runOnlyPendingTimersAsync()

异步相当于 jest.runOnlyPendingTimers()。它允许在运行计时器之前执行任何预定的 promise 回调。

¥Asynchronous equivalent of jest.runOnlyPendingTimers(). It allows any scheduled promise callbacks to execute before running the timers.

信息

当使用传统的假定时器实现时,此功能不可用。

¥This function is not available when using legacy fake timers implementation.

jest.advanceTimersToNextTimer(steps)

将所有计时器提前所需的毫秒,以便仅运行下一个超时/间隔。

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

或者,你可以提供 steps,因此它将运行 steps 次超时/间隔。

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

jest.advanceTimersToNextTimerAsync(steps)

异步相当于 jest.advanceTimersToNextTimer(steps)。它允许在运行计时器之前执行任何预定的 promise 回调。

¥Asynchronous equivalent of jest.advanceTimersToNextTimer(steps). It allows any scheduled promise callbacks to execute before running the timers.

信息

当使用传统的假定时器实现时,此功能不可用。

¥This function is not available when using legacy fake timers implementation.

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

返回当前时钟的时间(以毫秒为单位)。如果使用真实计时器,或者如果 Date 被模拟,则这相当于 Date.now()。在其他情况下(例如旧版计时器),它对于实现 Date.now()performance.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)

设置假定时器使用的当前系统时间。模拟用户在程序运行时更改系统时钟。它会影响当前时间,但它本身不会导致例如 定时器触发;他们将像没有调用 jest.setSystemTime() 时那样开火。

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

信息

当使用传统的假定时器实现时,此功能不可用。

¥This function is not available when using legacy fake timers implementation.

jest.getRealSystemTime()

当模拟的时候,Date.now() 也会被模拟。如果你出于某种原因需要访问当前的实时时间,你可以调用此函数。

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

信息

当使用传统的假定时器实现时,此功能不可用。

¥This function is not available when using legacy fake timers implementation.

杂项

¥Misc

jest.getSeed()

每次 Jest 运行时,都会随机生成一个种子值,你可以在伪随机数生成器或其他任何地方使用它。

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

提示

使用 --showSeed 标志打印测试报告摘要中的种子。要手动设置种子的值,请使用 --seed=<num> CLI 参数。

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

jest.isEnvironmentTornDown()

如果测试环境已被拆除,则返回 true

¥Returns true if test environment has been torn down.

jest.retryTimes(numRetries, options?)

运行失败的测试 n 次,直到它们通过或直到用尽最大重试次数。

¥Runs failed tests n-times until they pass or until the max number of retries is exhausted.

jest.retryTimes(3);

test('will fail', () => {
expect(true).toBe(false);
});

如果启用 logErrorsBeforeRetry 选项,导致测试失败的错误将记录到控制台。

¥If logErrorsBeforeRetry option is enabled, error(s) that caused the test to fail will be logged to the console.

jest.retryTimes(3, {logErrorsBeforeRetry: true});

test('will fail', () => {
expect(true).toBe(false);
});

返回用于链接的 jest 对象。

¥Returns the jest object for chaining.

提醒

jest.retryTimes() 必须在测试文件的顶层或 describe 块中声明。

¥jest.retryTimes() must be declared at the top level of a test file or in a describe block.

信息

此功能仅适用于默认的 jest-circus 运行器。

¥This function is only available with the default jest-circus runner.

jest.setTimeout(timeout)

设置测试文件中所有测试和之前/之后钩子的默认超时间隔(以毫秒为单位)。这仅影响调用该函数的测试文件。如果不调用该方法,默认超时时间为 5 秒。

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

示例:

¥Example:

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

要在同一文件中的不同测试上设置超时间隔,请使用 每个单独测试的 timeout 选项

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

如果要为所有测试文件设置超时,请使用 testTimeout 配置选项。

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