Jest 物件
jest
物件會自動出現在每個測試檔案的範圍內。jest
物件中的方法有助於建立模擬,並讓您控制 Jest 的整體行為。也可以透過 import {jest} from '@jest/globals'
明確匯入。
此頁面的 TypeScript 範例只有在您明確匯入 Jest API 時才會如文件所述運作
import {expect, jest, test} from '@jest/globals';
請參閱 入門 指南,了解如何使用 TypeScript 設定 Jest 的詳細資訊。
方法
- 模擬模組
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.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.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
建立新的深度複製物件。維護物件金鑰,並模擬其值。
Array
建立新的空陣列,忽略原始陣列。
基本型
建立一個新屬性,具有與原始屬性相同的基本型值。
範例
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'),
};
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)
當模組被需要時,使用自動模擬版本來模擬模組。factory
和 options
是選配的。例如
module.exports = () => 'banana';
jest.mock('../banana');
const banana = require('../banana'); // banana will be explicitly mocked.
banana(); // will return 'undefined' because the function is auto-mocked.
第二個參數可以用來指定一個明確的模組工廠,它會在執行時取代 Jest 的自動模擬功能
- JavaScript
- TypeScript
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';
// The optional type argument provides typings for the module factory
jest.mock<typeof import('../moduleName')>('../moduleName', () => {
return jest.fn(() => 42);
});
// This runs the function specified as second argument to `jest.mock`.
const moduleName = require('../moduleName');
moduleName(); // Will return '42';
當使用 factory
參數來處理具有預設匯出的 ES6 模組時,需要指定 __esModule: true
屬性。此屬性通常是由 Babel/TypeScript 產生的,但在此處需要手動設定。當匯入預設匯出時,它是一個指令,用於從匯出物件匯入名為 default
的屬性
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
第三個參數可以用來建立虛擬模擬,即模擬系統中不存在的模組
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
所指定)會阻止對該模組以及它匯入的所有模組進行模擬。
使用 jest.mock
進行模擬的模組只會對呼叫 jest.mock
的檔案進行模擬。另一個匯入模組的檔案將會取得原始實作,即使它是在模擬模組的測試檔案之後執行。
傳回 jest
物件以進行串連。
在 TypeScript 中撰寫測試?使用 jest.Mocked
實用程式類型或 jest.mocked()
輔助方法,讓您的模擬模組具有類型。
jest.Mocked<Source>
請參閱 Mock Functions 頁面的 TypeScript 使用方式 章節,以取得文件說明。
jest.mocked(source, options?)
請參閱 Mock Functions 頁面的 TypeScript 使用方式 章節,以取得文件說明。
jest.unmock(moduleName)
表示模組系統不應從 require()
傳回指定模組的 Mock 版本(例如,它應始終傳回真實模組)。
此 API 最常見的用途是指定特定測試打算測試的模組(因此不希望自動 Mock)。
傳回 jest
物件以進行串連。
jest.deepUnmock(moduleName)
表示模組系統不應傳回指定模組及其依賴項目的 Mock 版本。
傳回 jest
物件以進行串連。
jest.doMock(moduleName, factory, options)
使用 babel-jest
時,對 mock
的呼叫會自動提升至程式區塊的頂端。如果您想明確避免此行為,請使用此方法。
此方法在您想在同一個檔案中以不同方式 Mock 模組時會很有用。
- JavaScript
- TypeScript
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);
});
beforeEach(() => {
jest.resetModules();
});
test('moduleName 1', () => {
// The optional type argument provides typings for the module factory
jest.doMock<typeof import('../moduleName')>('../moduleName', () => {
return jest.fn(() => 1);
});
const moduleName = require('../moduleName');
expect(moduleName()).toBe(1);
});
test('moduleName 2', () => {
jest.doMock<typeof import('../moduleName')>('../moduleName', () => {
return jest.fn(() => 2);
});
const moduleName = require('../moduleName');
expect(moduleName()).toBe(2);
});
在 ES6 匯入中使用 jest.doMock()
需要額外的步驟。如果您不想在測試中使用 require
,請遵循下列步驟
- 我們必須指定
__esModule: true
屬性(請參閱jest.mock()
API 以取得更多資訊)。 - 靜態 ES6 模組匯入會提升至檔案的頂端,因此我們必須使用
import()
動態匯入它們。 - 最後,我們需要支援動態匯入的環境。請參閱 使用 Babel 以取得初始設定。然後將 babel-plugin-dynamic-import-node 外掛程式,或等效外掛程式,新增至您的 Babel 設定檔,以在 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
物件以進行串連。
jest.dontMock(moduleName)
使用 babel-jest
時,對 unmock
的呼叫會自動提升至程式區塊的頂端。如果您想明確避免此行為,請使用此方法。
傳回 jest
物件以進行串連。
jest.setMock(moduleName, moduleExports)
明確提供模組系統應該為指定模組回傳的模擬物件。
偶爾,模組系統自動產生的模擬物件無法滿足您的測試需求。通常在這種情況下,您應該撰寫一個更適合該模組的手動模擬物件。然而,在極少數情況下,即使手動模擬物件也不適合您的目的,您需要在測試中自行建立模擬物件。
在這些罕見的情況下,您可以使用此 API 手動填入模組系統的模擬模組註冊表中的插槽。
傳回 jest
物件以進行串連。
建議改用jest.mock()
。jest.mock
API 的第二個參數是模組工廠,而不是預期的匯出模組物件。
jest.requireActual(moduleName)
傳回實際模組,而不是模擬物件,略過所有模組是否應該接收模擬實作的檢查。
- JavaScript
- TypeScript
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.mock('../myModule', () => {
// Require the original module to not be mocked...
const originalModule =
jest.requireActual<typeof import('../myModule')>('../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)
傳回模擬模組,而不是實際模組,略過所有模組是否應該正常需要的檢查。
jest.resetModules()
重設模組註冊表,也就是所有已載入模組的快取。這有助於隔離模組,其中區域狀態可能會在測試之間產生衝突。
範例
const sum1 = require('../sum');
jest.resetModules();
const sum2 = require('../sum');
sum1 === sum2;
// > false (Both sum modules are separate "instances" of the sum module.)
測試範例
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
物件以進行串連。
jest.isolateModules(fn)
jest.isolateModules(fn)
比jest.resetModules()
更進一步,並為在回呼函式內載入的模組建立一個沙盒註冊表。這有助於為每個測試隔離特定模組,讓區域模組狀態不會在測試之間產生衝突。
let myModule;
jest.isolateModules(() => {
myModule = require('myModule');
});
const otherCopyOfMyModule = require('myModule');
jest.isolateModulesAsync(fn)
jest.isolateModulesAsync()
等於jest.isolateModules()
,但適用於非同步回呼。呼叫者預期會await
isolateModulesAsync
完成。
let myModule;
await jest.isolateModulesAsync(async () => {
myModule = await import('myModule');
// do async stuff here
});
const otherCopyOfMyModule = await import('myModule');
模擬函式
jest.fn(implementation?)
傳回一個新的、未使用的模擬函式。選擇性地採用模擬實作。
const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();
// With a mock implementation:
const returnsTrue = jest.fn(() => true);
console.log(returnsTrue()); // true;
請參閱模擬函式頁面,以取得 TypeScript 使用方式的詳細資訊。
jest.isMockFunction(fn)
判斷給定的函式是否為模擬函式。
jest.replaceProperty(object, propertyKey, value)
使用 value
替換 object[propertyKey]
。該屬性必須已存在於物件中。同一個屬性可以被替換多次。傳回一個 Jest 已替換屬性。
若要模擬定義為 getter 或 setter 的屬性,請改用 jest.spyOn(object, methodName, accessType)
。若要模擬函式,請改用 jest.spyOn(object, methodName)
。
所有使用 jest.replaceProperty
替換的屬性,都可以透過在 afterEach 方法中呼叫 jest.restoreAllMocks 來還原為原始值。
範例
const utils = {
isLocalhost() {
return process.env.HOSTNAME === 'localhost';
},
};
module.exports = utils;
範例測試
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 模擬函式。
預設情況下,jest.spyOn
也會呼叫被偵測的方法。這與大多數其他測試函式庫的行為不同。如果您想覆寫原始函式,可以使用 jest.spyOn(object, methodName).mockImplementation(() => customImplementation)
或 object[methodName] = jest.fn(() => customImplementation)
。
由於 jest.spyOn
是模擬,因此您可以透過在傳遞給 afterEach 勾子的回呼函式中呼叫 jest.restoreAllMocks
來還原初始狀態。
範例
const video = {
play() {
return true;
},
};
module.exports = video;
範例測試
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 時,這會很有用。
範例
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;
範例測試
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>
請參閱 Mock Functions 頁面的 TypeScript 使用 章節以取得文件。
jest.Spied<Source>
請參閱 Mock Functions 頁面的 TypeScript 使用 章節以取得文件。
jest.clearAllMocks()
清除所有 Mock 的 mock.calls
、mock.instances
、mock.contexts
和 mock.results
屬性。等同於對每個 Mock 函式呼叫 .mockClear()
。
傳回 jest
物件以進行串連。
jest.resetAllMocks()
重設所有 Mock 的狀態。等同於對每個 Mock 函式呼叫 .mockReset()
。
傳回 jest
物件以進行串連。
jest.restoreAllMocks()
將所有 Mock 和已取代的屬性還原為其原始值。等同於對每個 Mock 函式呼叫 .mockRestore()
,並對每個已取代的屬性呼叫 .restore()
。請注意,jest.restoreAllMocks()
僅適用於使用 jest.spyOn()
建立的 Mock,以及使用 jest.replaceProperty()
取代的屬性;其他 Mock 需要您手動還原。
假時間
jest.useFakeTimers(fakeTimersConfig?)
指示 Jest 使用全域日期、效能、時間和計時器 API 的假版本。假時間實作由 @sinonjs/fake-timers
支援。
假計時器會用從假時鐘取得時間的實作替換 Date
、performance.now()
、queueMicrotask()
、setImmediate()
、clearImmediate()
、setInterval()
、clearInterval()
、setTimeout()
、clearTimeout()
。
在 Node 環境中,process.hrtime
、process.nextTick()
,在 JSDOM 環境中,requestAnimationFrame()
、cancelAnimationFrame()
、requestIdleCallback()
、cancelIdleCallback()
也會被替換。
組態選項
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()
還原原始計時器。
你可以從任何地方呼叫 jest.useFakeTimers()
或 jest.useRealTimers()
:頂層、test
區塊內等等。請記住,這是全域操作,會影響同一個檔案中的其他測試。在同一個測試檔案中再次呼叫 jest.useFakeTimers()
會重設內部狀態(例如計時器計數),並使用提供的選項重新安裝假計時器
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();
// ...
});
由於某種原因,你可能必須使用舊版假計時器實作。可以這樣啟用(不支援額外選項)
jest.useFakeTimers({
legacyFakeTimers: true,
});
舊版假計時器會用 Jest 模擬函式替換 setImmediate()
、clearImmediate()
、setInterval()
、clearInterval()
、setTimeout()
、clearTimeout()
。在 Node 環境中,process.nextTick()
,在 JSDOM 環境中,requestAnimationFrame()
、cancelAnimationFrame()
也會被替換。
傳回 jest
物件以進行串連。
jest.useRealTimers()
指示 Jest 還原全域日期、效能、時間和計時器 API 的原始實作。例如,你可以在 afterEach
鉤子中呼叫 jest.useRealTimers()
,在每個測試後還原計時器
afterEach(() => {
jest.useRealTimers();
});
test('do something with fake timers', () => {
jest.useFakeTimers();
// ...
});
test('do something with real timers', () => {
// ...
});
傳回 jest
物件以進行串連。
jest.runAllTicks()
耗盡微任務佇列(通常透過 process.nextTick
在 node 中介面)。
當呼叫此 API 時,所有已透過 process.nextTick
排隊的待處理微任務都會執行。此外,如果這些微任務本身排程新的微任務,這些微任務會持續耗盡,直到佇列中沒有更多微任務為止。
jest.runAllTimers()
耗盡巨集任務佇列(即由 setTimeout()
、setInterval()
和 setImmediate()
排隊的所有任務)和微任務佇列(通常透過 process.nextTick
在 node 中介面)。
呼叫此 API 時,所有待處理的巨型任務和微型任務都會執行。如果這些任務本身排程新的任務,這些任務會持續耗盡,直到佇列中沒有更多任務為止。
這通常可用於在測試期間同步執行 setTimeout,以便在 setTimeout()
或 setInterval()
回呼執行後才會發生的某些行為上同步斷言。請參閱 Timer mocks 文件以取得更多資訊。
jest.runAllTimersAsync()
jest.runAllTimers()
的非同步等效項。它允許在執行計時器之前執行任何排程的 Promise 回呼。
使用舊版假計時器實作時,此函式不可用。
jest.runAllImmediates()
耗盡由 setImmediate()
排隊的所有任務。
使用舊版假計時器實作時,此函式才可用。
jest.advanceTimersByTime(msToRun)
僅執行巨型任務佇列(即,由 setTimeout()
或 setInterval()
和 setImmediate()
排隊的所有任務)。
呼叫此 API 時,所有計時器都會提前 msToRun
毫秒。所有透過 setTimeout()
或 setInterval()
排隊,且會在此時間範圍內執行的待處理「巨型任務」都會執行。此外,如果這些巨型任務排程會在同一個時間範圍內執行的新的巨型任務,這些任務會執行,直到佇列中沒有更多應該在 msToRun
毫秒內執行的巨型任務為止。
jest.advanceTimersByTimeAsync(msToRun)
jest.advanceTimersByTime(msToRun)
的非同步等效項。它允許在執行計時器之前執行任何排程的 Promise 回呼。
使用舊版假計時器實作時,此函式不可用。
jest.runOnlyPendingTimers()
僅執行目前待處理的巨型任務(即,僅執行到目前為止由 setTimeout()
或 setInterval()
排隊的任務)。如果任何目前待處理的巨型任務排程新的巨型任務,此呼叫不會執行這些新任務。
這對於以下情況很有用:受測模組排程一個 setTimeout()
,其回呼遞迴排程另一個 setTimeout()
(表示排程永遠不會停止)。在這些情況下,能夠一次執行一個步驟向前跳躍很有用。
jest.runOnlyPendingTimersAsync()
jest.runOnlyPendingTimers()
的非同步等效項。它允許任何排程的 Promise 回呼在執行計時器之前執行。
使用舊版假計時器實作時,此函式不可用。
jest.advanceTimersToNextTimer(steps)
將所有計時器推進必要的毫秒數,以便只執行下一個逾時/間隔。
您也可以提供 steps
,這樣它將執行 steps
數量的下一個逾時/間隔。
jest.advanceTimersToNextTimerAsync(steps)
jest.advanceTimersToNextTimer(steps)
的非同步等效項。它允許任何排程的 Promise 回呼在執行計時器之前執行。
使用舊版假計時器實作時,此函式不可用。
jest.clearAllTimers()
從計時器系統中移除任何待處理的計時器。
這表示,如果已排程任何計時器(但尚未執行),它們將被清除,且永遠不會有機會在未來執行。
jest.getTimerCount()
傳回仍剩餘執行的人工計時器數量。
jest.now()
傳回目前時鐘的毫秒時間。如果使用真實計時器,這等於 Date.now()
,或如果模擬 Date
。在其他情況(例如舊式計時器)中,它可能有助於實作 Date.now()
、performance.now()
等的客製模擬。
jest.setSystemTime(now?: number | Date)
設定人工計時器使用的目前系統時間。模擬使用者在程式執行期間變更系統時鐘。它會影響目前時間,但本身不會導致例如計時器觸發;它們將完全按照沒有呼叫 jest.setSystemTime()
的情況觸發。
使用舊版假計時器實作時,此函式不可用。
jest.getRealSystemTime()
在模擬時間時,Date.now()
也會被模擬。如果你因為某些原因需要存取實際的目前時間,你可以呼叫這個函式。
使用舊版假計時器實作時,此函式不可用。
雜項
jest.getSeed()
每次 Jest 執行時,會隨機產生一個種子值,你可以在偽亂數產生器或其他地方使用它。
使用 --showSeed
旗標在測試報告摘要中列印種子。若要手動設定種子的值,請使用 --seed=<num>
CLI 參數。
jest.isEnvironmentTornDown()
如果測試環境已中斷,則傳回 true
。
jest.retryTimes(numRetries, options?)
執行失敗的測試 n 次,直到它們通過或直到重試次數用盡。
jest.retryTimes(3);
test('will fail', () => {
expect(true).toBe(false);
});
如果啟用 logErrorsBeforeRetry
選項,導致測試失敗的錯誤將記錄到主控台。
jest.retryTimes(3, {logErrorsBeforeRetry: true});
test('will fail', () => {
expect(true).toBe(false);
});
傳回 jest
物件以進行串連。
jest.retryTimes()
必須宣告在測試檔案的最上層或在 describe
區塊中。
此函式僅在預設的 jest-circus 執行器中可用。
jest.setTimeout(timeout)
設定測試檔案中所有測試和 before/after 掛鉤的預設逾時間隔(以毫秒為單位)。這只會影響呼叫此函式的測試檔案。如果未呼叫此方法,預設逾時間隔為 5 秒。
範例
jest.setTimeout(1000); // 1 second
若要在同一個檔案中設定不同測試的逾時間隔,請在每個個別測試中使用 timeout
選項。
如果您想要設定所有測試檔案的逾時時間,請使用 testTimeout
組態選項。