Перейти до основного змісту
Версія: 29.1

Об’єкт Jest

Об'єкт jest автоматично знаходиться в контексті кожного тестового файлу. Методи в об'єкті jest допомагають створити імітації та дозволяють контролювати загальну поведінку Jest. Також його можна імпортувати явно через import {jest} from '@jest/globals'.

info

Приклади TypeScript з цієї сторінки будуть працювати, як задокументовано, тільки якщо ви явно імпортуєте Jest API:

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

Інструкцію щодо налаштування Jest за допомогою TypeScript можна знайти на сторінці Початок роботи.

Методи


Mock Modules

jest.disableAutomock()

Вимикає автоматичну генерацію імітацій в завантажувачі модулів.

info

Аби цей метод працював, автоматичне створення імітацій повинно бути увімкнено за допомогою параметру конфігурації automock. Більш детальну інформацію шукайте в документації параметру конфігурації.

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

module.exports = config;

Після того, як буде викликаний disableAutomock(), всі виклики require() будуть повертати реальні версії модулів (замість їх імітацій).

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

Зазвичай це буває корисно, коли у вас є сценарій, в якому кількість залежностей, для яких потрібно створити імітації, значно менша, ніж тих, для яких імітації не потрібні. Наприклад, якщо ви пишете тест для модуля, який використовує велику кількість залежностей, що можуть бути класифіковані як "деталі реалізації" модуля, тоді вам, схоже, не потрібно створювати імітації для них усіх.

Приклади залежностей, які можуть бути розцінені як "деталі реалізації", починаються з вбудованих методів мови (такі як методи Array.prototype) і закінчуються дуже поширеними допоміжними методами (наприклад, underscore, lodash, і так далі) чи навіть цілими бібліотеками типу React.js.

Повертає об’єкт jest для створення ланцюжків викликів.

порада

Коли ви використовуєте babel-jest, виклики disableAutomock() будуть автоматично спливати до початку блоку коду. Використовуйте autoMockOff(), якщо ви хочете явно заборонити таку поведінку.

jest.enableAutomock()

Вмикає автоматичну генерацію імітацій в завантажувачі модулів.

info

Докладнішу інформацію про автоматичне створення імітацій шукайте в документації параметру конфігурації automock.

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 для створення ланцюжків викликів.

порада

Коли ви використовуєте babel-jest, виклики enableAutomock будуть автоматично спливати до початку блоку коду. Використовуйте autoMockOn, якщо ви хочете явно заборонити таку поведінку.

jest.createMockFromModule(moduleName)

На основі заданого модуля, використовує систему автоматичного створення імітацій для створення імітації модуля.

Це корисно, коли ви хочете створити ручну імітацію, яка розширює поведінку автоматично створеної імітації модуля:

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

This is how createMockFromModule will mock the following data types:

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', () => {
// створює нову імітовану функцію без аргументів.
expect(example.function.name).toBe('square');
expect(example.function).toHaveLength(0);

// асинхронні функції обробляються аналогічно до стандартних синхронних функцій.
expect(example.asyncFunction.name).toBe('asyncSquare');
expect(example.asyncFunction).toHaveLength(0);

// створює новий клас з таким самим інтерфейсом; функції-члени та властивості імітуються.
expect(example.class.constructor.name).toBe('Bar');
expect(example.class.foo.name).toBe('foo');
expect(example.class.array).toHaveLength(0);

// створює глибокий клон оригінального об'єкта.
expect(example.object).toEqual({
baz: 'foo',
bar: {
fiz: 1,
buzz: [],
},
});

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

// створює нову властивість з примітивними значеннями оригінального об'єкта.
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)

Mocks a module with an auto-mocked version when it is being required. factory and options are optional. Наприклад:

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

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

Третій параметр можу бути використаний для створення віртуальних імітацій - таких, які не існують ніде в системі:

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

Імпорт модуля в файл налаштування (вказаний в setupFilesAfterEnv) буде перешкоджати створенню імітації для нього, як і для всіх модулів, які він імпортує.

Модулі, для яких створені імітації з допомогою jest.mock є імітаціями тільки в межах файлу, в якому було викликано 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 для створення ланцюжків викликів.

порада

Writing tests in TypeScript? Використовуйте тип утиліти jest.Mocked або допоміжний метод jest.mocked(), щоб вказати тип імітованих модулів.

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)

Вказує, що система модулів не повинна повертати імітацію конкретного модуля та його залежностей.

Повертає об’єкт 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.

Це може бути корисно, коли ви хочете по-різному імітувати модуль в межах одного і того ж файла з тестами:

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

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 для додаткової інформації).
  • Статичні імпорти модуля 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 будуть автоматично спливати до початку блоку коду. Use this method if you want to explicitly avoid this behavior.

Повертає об’єкт 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. Normally under those circumstances you should write a manual mock that is more adequate for the module in question. Однак в екстремально рідкісних випадках навіть ручний мок не підходить для ваших цілей і вам потрібно створити імітацію всередині вашого тесту.

В таких рідкісних сценаріях ви можете використати цей API, щоб в ручну заповнити слот в реєстрі імітацій системи модулів.

Повертає об’єкт jest для створення ланцюжків викликів.

info

Рекомендується використовувати jest.mock() замість цього метода. Другий аргумент jest.mock - це функція, яка повертає імітацію замість очікуваного об’єкта модуля.

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, // Використовуйте під час роботи з esModules
...originalModule,
getRandom: jest.fn(() => 10),
};
});

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

getRandom(); // Завжди повертає 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 (sum1 і sum2 є різними екземплярами модуля "sum".)

Приклад в тесті:

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

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

test('works too', () => {
const sum = require('../sum');
// змінна sum – це інша копія модуля "sum" у порівнянні з попереднім тестом.
});

Повертає об’єкт 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.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 дивіться на сторінці Функції-імітації.

jest.isMockFunction(fn)

Визначає, чи задана функція є імітацією.

jest.spyOn(object, methodName)

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

note

By default, jest.spyOn also calls the spied method. Це відміна поведінка у порівнянні з більшістю інших тестових бібліотек. Якщо ви очете переписати оригінальну функцію, ви можете використати jest.spyOn(object, methodName).mockImplementation(() => customImplementation) або object[methodName] = jest.fn(() => customImplementation);

порада

Через те, що jest.spyOn є імітацією, ви можете відновити початкове значення викликом jest.restoreAllMocks всередині зворотного виклику, переданого хуку afterEach.

Example:

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

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;

Приклад тесту:

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

afterEach(() => {
// відновлення слідкування, створеного за допомогою spyOn
jest.restoreAllMocks();
});

test('plays video', () => {
const spy = jest.spyOn(video, 'play', 'get'); // передаємо 'get'
const isPlaying = video.play();

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

test('plays audio', () => {
const spy = jest.spyOn(audio, 'volume', 'set'); // передаємо 'set'
audio.volume = 100;

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

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

Скидає всі імітації до їх оригінальних значень. Equivalent to calling .mockRestore() on every mocked function. Beware that jest.restoreAllMocks() only works when the mock was created with jest.spyOn; other mocks will require you to manually restore them.

Фіктивні таймери

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

Виконує всі мікрозавдання в черзі (зазвичай створені в Node з допомогою process.nextTick).

Коли викликається цей метод, всі мікрозавдання, заплановані через process.nextTick будуть виконані. Додатково, якщо ці мікрозавдання самі планують нові мікрозавдання, вони теж будуть постійно виконуватися поки в черзі не залишиться жодного мікрозавдання.

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.

Це часто буває корисно для синхронного виконання setTimeout’ів впродовж тесту для синхронної перевіки якоїсь поведінки, яка відбувається лише після виконання зворотніх викликів в setTimeout() або setInterval(). See the Timer mocks doc for more information.

jest.runAllImmediates()

Виконує всі завдання, заплановані з використанням setImmediate().

info

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

jest.advanceTimersByTime(msToRun)

Виконує лише макрозавдання з черги (заплановані, використовуючи setTimeout(), setInterval() та setImmediate()).

Коли викликається цей метод, всі таймери наближаються на msToRun мілісекунд. 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.runOnlyPendingTimers()

Виконує лише ті макрозавдання, які в даний час заплановані (тобто лише завдання, які були поставлені в чергу за допомогою setTimeout() чи setInterval() до цього моменту). Якщо будь яке з запланованих макрозавдань запланує нове макрозавдання, ті нові завдання не будуть виконані цим викликом.

Це корисно для сценаріїв, коли модуль, що тестується, викликає setTimeout(), зворотній виклик якого рекурсивно викликає інший setTimeout() (що означає, що послідовність таймаутів ніколи не припинеться). У таких сценаріях корисно мати можливість рухатися вперед в часі на один крок за раз.

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)

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

info

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

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.

info

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

Misc

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

Якщо параметр logErrorsBeforeRetry увімкнено, то помилки, які призвели до падіння тесту, будуть виведені в консолі.

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

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

Повертає об’єкт jest для створення ланцюжків викликів.

caution

jest.retryTimes() повинен оголошуватись на верхньому рівні тестового файлу або в блоці describe.

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. 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 секунда
порада

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.