Jest 对象
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
jest 对象在每个测试文件中自动处于作用域内。jest 对象的方法可帮助创建模拟(mock)并控制 Jest 的整体行为,也可通过 import {jest} from '@jest/globals' 显式导入。
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
本页中的 TypeScript 示例仅在显式导入 Jest API 的情况下才能按文档所述正常工作:
import {expect, jest, test} from '@jest/globals';
有关如何设置 Jest 与 TypeScript 配合使用的详细信息,请查阅入门指南。
方法
- 模块模拟
jest.disableAutomock()jest.enableAutomock()jest.createMockFromModule(moduleName)jest.mock(moduleName, factory, options)jest.Mocked<Source>jest.mocked(source, options?)jest.unmock(moduleName)jest.deepUnmock(moduleName)jest.doMock(moduleName, factory, options)jest.dontMock(moduleName)jest.setMock(moduleName, moduleExports)jest.requireActual(moduleName)jest.requireMock(moduleName)jest.onGenerateMock(cb)jest.resetModules()jest.isolateModules(fn)jest.isolateModulesAsync(fn)
- 模拟函数
- 假计时器
jest.useFakeTimers(fakeTimersConfig?)jest.useRealTimers()jest.runAllTicks()jest.runAllTimers()jest.runAllTimersAsync()jest.runAllImmediates()jest.advanceTimersByTime(msToRun)jest.advanceTimersByTimeAsync(msToRun)jest.runOnlyPendingTimers()jest.runOnlyPendingTimersAsync()jest.advanceTimersToNextTimer(steps)jest.advanceTimersToNextTimerAsync(steps)jest.advanceTimersToNextFrame()jest.clearAllTimers()jest.getTimerCount()jest.now()jest.setSystemTime(now?: number | Date)jest.getRealSystemTime()
- 其他功能
模块模拟
jest.disableAutomock()
禁用模块加载器中的自动模拟功能。
此方法生效的前提是已通过 automock 配置选项启用自动模拟功能。具体配置细节请参阅相关文档。
- JavaScript
- TypeScript
/** @type {import('jest').Config} */
const config = {
automock: true,
};
module.exports = config;
import type {Config} from 'jest';
const config: Config = {
automock: true,
};
export default config;
调用 disableAutomock() 后,所有 require() 将返回模块的真实版本(而非模拟版本)。
export default {
authorize: () => {
return 'token';
},
};
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');
});
此方法适用于需模拟的依赖远少于不需模拟依赖的场景。例如测试某模块时,若其大量依赖属于"实现细节"范畴(如语言内置方法),通常无需模拟这些依赖。
"实现细节"类依赖包括:语言内置对象(如 Array.prototype 方法)、常用工具库(如 underscore, lodash)以及 React.js 等完整库。
返回 jest 对象以支持链式调用。
使用 babel-jest 时,disableAutomock() 调用会自动提升至代码块顶部。如需显式避免此行为,请改用 autoMockOff()。
jest.enableAutomock()
启用模块加载器中的自动模拟功能。
自动模拟功能详情请参阅 automock 配置选项文档。
示例:
export default {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
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 对象以支持链式调用。
使用 babel-jest 时,enableAutomock 调用会自动提升至代码块顶部。如需显式避免此行为,请改用 autoMockOn。
jest.createMockFromModule(moduleName)
根据模块名称,通过自动模拟系统生成该模块的模拟版本。
适用于扩展自动模拟行为的手动模拟场景:
- JavaScript
- TypeScript
module.exports = {
authorize: () => {
return 'token';
},
isAuthorized: secret => secret === 'wizard',
};
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);
});
export const utils = {
authorize: () => {
return 'token';
},
isAuthorized: (secret: string) => secret === 'wizard',
};
const {utils} =
jest.createMockFromModule<typeof import('../utils')>('../utils');
utils.isAuthorized = jest.fn((secret: string) => secret === 'not wizard');
test('implementation created by jest.createMockFromModule', () => {
expect(jest.isMockFunction(utils.authorize)).toBe(true);
expect(utils.isAuthorized('not wizard')).toBe(true);
});
createMockFromModule 对各类数据的模拟方式如下:
Function
创建新的模拟函数。该函数无形式参数,调用时返回 undefined,此特性同样适用于 async 函数。
Class
创建新类。保留原始类接口,但所有成员方法和属性均会被模拟。
Object
创建深度克隆的新对象。保留对象键名,但键值会被模拟。