メインコンテンツへスキップ
Version: 29.4

Jestオブジェクト

jest オブジェクトは、すべてのテストファイル内で自動的にスコープされます。 jest オブジェクトのメソッドはモックの作成に役立ち、Jestの全体的な動作を制御できます。 import {jest} from '@jest/globals' を介して明示的にインポートすることもできます。

info

このページの TypeScript の例は、次のように Jest の API を明示的にインポートした場合にのみ動作します。

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

TypeScript で Jest をセットアップする方法の詳細については、Getting Started ガイドを参照してください。

メソッド


モックモジュール

jest.disableAutomock()

モジュールローダーの自動モック機能を無効にします。

info

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;

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

この関数はモックしたい依存関係が、モックが要らないものよりもはるかに少ないシナリオがある場合に便利です。 例えば、"implementation details"として分類されるのが妥当な大量の依存関係を持つモジュールのテスト書く場合、それらをモックしたいとは思わないでしょう。

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オブジェクトを返します。

tip

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

モジュールローダーで自動モック機能を有効化します。

info

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

例:

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オブジェクトを返します。

tip

babel-jestを使用している場合は、enableAutomockの呼び出しは自動的にコードの先頭で行われます。 この動作を避けるにはautoMockOn を明示的に使用して下さい。

jest.createMockFromModule(moduleName)

与えられた名前のモジュールに対して自動モック化システムを利用してモック化したモジュールを作成します。

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 が以下のデータ型をモックする方法です。

関数

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.

クラス

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 empty array, ignoring the original.

プリミティブ型

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

例:

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)

requireされた際に自動モック化されたモジュールのモックを作成します。 factoryoptionsはオプションです。 例:

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.

第2引数はJestの自動モックによる設定を用いる代わりに明示的にモジュールのファクトリを指定する場合に使用します。

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 という名前のプロパティをインポートします。

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

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

moduleName(); // 42を返します
foo(); // 43を返します

第3引数は仮想モックを作成するのに使用します - これはシステム内のどこにも存在しないモジュールのモックです。

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},
);
caution

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を呼び出したファイル内でのみモックされます。 モジュールをモックしたテストの後に実行したとしても、そのモジュールをインポートする別のファイルでは、本物のモジュールがインポートされます。

メソッドチェーンのためにjestオブジェクトを返します。

tip

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)

指定したモジュールについてrequire()した際に、モジュールシステムは決してモックしたものを返さないことを設定します(例えば常に本物のモジュールを返すべき場合など)。

このAPIの最も一般的な用途は、指定されたモジュールを与えられたテストファイルでテストしようとしている場合(そのため自動的にモックをしたくない場合) です。

メソッドチェーンのために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)

babel-jestを使用している場合、 mock の呼び出しは自動的にコードブロックの先頭で行われます。 この振る舞いを明示的に避けるにはこのメソッドを使用してください。

この関数が有用な例の1つとして、同一ファイル内で異なる振る舞いのモックを使用したい場合が挙げられます:

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);
});

ES6 インポートで jest.doMock() を使用するには、追加の手順が必要です。 テストで require を使用したくない場合は、次の手順に従ってください。

  • __esModule: true プロパティを指定する必要があります (詳細については jest.mock() API を参照してください)。
  • 静的ES6モジュールのインポートはファイルの先頭で行われてしまうので、代わりに import() を使用して動的にインポートする必要があります。
  • 最後に、動的インポートをサポートする環境が必要です。 初期設定については、 Using 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)

指定されたモジュールについてモジュールシステムが返すべきモックオブジェクトを明示的に与えます。

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. 通常そのような状況では当該のモジュールにより適したマニュアルモックを作成するべきです。 しかしとても稀ですが、マニュアルモックですら目的に対して適切でなくテスト内でモックを作成する必要があるケースがあります。

これらの稀なシナリオでは、このAPIでモジュールシステムのモックモジュールのレジストリのスロットに手動で設定することができます。

メソッドチェーンのためにjestオブジェクトを返します。

info

It is recommended to use jest.mock() instead. jest.mockAPIの第2引数はエクスポートされたモジュールのオブジェクトの代替となるモジュールのファクトリを指定できます。

jest.requireActual(moduleName)

モジュールがモックしたものを受け取る設定であるかを確認せず、モックではない本物のモジュールを返すようになります。

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)

モジュールが通常通りrequireされるかを確認せず、本物のモジュールではないモックを返すようになります。

jest.resetModules()

モジュールのレジストリ - 全てのrequireされたモジュール - をリセットします 。 テスト間でローカルの状態が競合しうるモジュールの状態をテストごとに切り離すのに役立ちます。

例:

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

モック関数

jest.fn(implementation?)

新しい、未使用のモック関数を返します。 オプションでモックに対する実装を受け取ります。

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

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

See the Mock Functions page for details on TypeScript usage.

jest.isMockFunction(fn)

与えられた関数がモック関数がどうかを返します。

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.

note

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.

tip

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

例:

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の モック関数を返します。

note

By default, jest.spyOn also calls the spied method. これは他の大抵のテストライブラリとは異なる振る舞いです。 If you want to overwrite the original function, you can use jest.spyOn(object, methodName).mockImplementation(() => customImplementation) or object[methodName] = jest.fn(() => customImplementation).

tip

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.

例:

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 メソッドはオプションの第3引数 accessType を取るようになりました。 この引数には 'get' または 'set' を指定することができ、それぞれゲッタやセッタをスパイしたい場合に便利です。

例:

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>

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

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

メソッドチェーンのためにjestオブジェクトを返します。

jest.resetAllMocks()

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.

Fake Timers

jest.useFakeTimers(fakeTimersConfig?)

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

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.

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;
};

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

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();
// ...
});
Legacy Fake Timers

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,
});

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オブジェクトを返します。

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オブジェクトを返します。

jest.runAllTicks()

micro-task キューを処理します(通常はnodeでprocess.nextTick経由でやり取りします)。

このAPIが呼ばれた場合、process.nextTick経由でキューイングされた全ての保留中のmicro-taskが実行されます。 さらに、それらmicro-task自身が新しいmicro-taskをスケジュールしている場合は、キューからmicro-taskが無くなるまで継続的に処理されます。

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.

このAPIは setTimeout()setInterval()コールバックが実行された後でのみ発生するような動作を同期して確認するために、テスト中に同期的にsetTimeouts関数を動作させる場合に便利です。 詳細については Timer mocks ドキュメントを参照してください。

jest.runAllImmediates()

setImmediate() によってキューイングされた全てのタスクを処理します。

info

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

jest.advanceTimersByTime(msToRun)

macro taskキューのみを実行します(つまり、 setTimeout()setInterval()setImmediate()によってキューイングされた全てのタスクです)。

この API が呼び出されると、すべてのタイマーは msToRun ミリ秒で進みます。 このタイムフレームで実行されるであろう、全ての setTimeout() または setInterval() 経由でキューイングされた保留中の "macro-tasks" が実行されます。 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()

現時点で保留中のmacro-taskのみを実行します(つまりこの時点までにsetTimeout()setInterval()によってキューイングされたタスクのみです)。 その時点で保留中の macro-tasksが新しい macro-taskをスケジュールしている場合、それらの新しいタスクはこのAPIからの呼び出しでは実行されません。

このAPIはテスト対象のモジュールがsetTimeout()が新たなsetTimeout()をコールバック内で再帰的にスケジュールしているようなシナリオに役立ちます(コールバック内のスケジューリングは停止しないということです) これらのシナリオでは、一度に1回ずつ時間を進めることができる事が便利なのです。 これらのシナリオでは、一度に1回ずつ時間を進めることができる事が便利なのです。

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

タイマーシステムが保留しているあらゆるタイマーを削除します。

つまり、(まだ実行されていない) スケジュールされた全てのタイマーについて、削除され、将来にわたって実行されることはないという事です。

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)

偽のタイマーで使用される現在システム時刻を設定します。 プログラム実行中のユーザーによるシステムクロックの変更するシミュレートします。 現在の時刻に影響しますが、例えば起動タイマのような、それ自体の内部で発生するものには影響しません。 jest.setSystemTime() が呼び出されなかった場合と同様に、正確に起動します。

info

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

jest.getRealSystemTime()

時刻をモックしている場合、 Date.now() もモックされます。 何らかの理由で本当の現在時刻にアクセスする必要がある場合は、この関数を呼び出すことができます。

info

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

その他

jest.getSeed()

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

tip

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

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.

jest.retryTimes(3);

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

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オブジェクトを返します。

caution

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

info

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

jest.setTimeout(timeout)

Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. これはこの関数が呼び出されたテストファイルにのみ影響します。 The default timeout interval is 5 seconds if this method is not called.

例:

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

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.