Об’єкт Jest
Об'єкт jest
автоматично знаходиться в контексті кожного тестового файлу. Методи в об'єкті jest
допомагають створити імітації та дозволяють контролювати загальну поведінку Jest. Також його можна імпортувати явно через import {jest} from '@jest/globals'
.
Приклади TypeScript з цієї сторінки будуть працювати, як задокументовано, тільки якщо ви явно імпортуєте Jest API:
import {expect, jest, test} from '@jest/globals';
Інструкцію щодо налаштування Jest за допомогою TypeScript можна знайти на сторінці Початок роботи.
Методи
- Mock Modules
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.advanceTimersToNextFrame()
jest.clearAllTimers()
jest.getTimerCount()
jest.now()
jest.setSystemTime(now?: number | Date)
jest.getRealSystemTime()
- Misc
Mock Modules
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');
});