Объект Jest
The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via import {jest} from '@jest/globals'.
Примеры TypeScript с этой страницы будут работать только в том случае, если вы явно импортируете Jest API:
Import {expect, jest, test} from '@jest/globals';
Consult the Getting Started guide for details on how to setup Jest with TypeScript.
Методы
- Mock Модули
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)
- Mock-функции
- Fake Timers
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.setTimerTickMode(mode)jest.getRealSystemTime()
- Misc
Mock Модули
jest.disableAutomock()
Отключает автоматическое создание mock-объектов в загрузчике модулей.
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.
- 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;
After disableAutomock() is called, all require()s will return the real versions of each module (rather than a mocked version).
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');
});
Это обычно полезно, когда у вас есть сценарий, где количество зависимостей, которые вы хотите сымитировать, гораздо меньше, чем количество зав исимостей, для которых это не требуется. Например, если вы пишете тест для модуля, который использует большое число зависимостей, которые могут быть расценены, как «детали реализации» модуля, то вы, вероятно, не захотите их имитировать.
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.
Returns the jest object for chaining.
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.