Объект Jest
Объект jest
автоматически создается в глобальной области видимости каждого тестового файла. Метод ы объекта jest
помогают создать mock-классы/функции/переменные и позволить вам контролировать общее поведение Jest'а. Также он может быть явно импортирован через import {jest} from '@jest/globals'
.
Примеры TypeScript с этой страницы будут работать только в том случае, если вы явно импортируете Jest API:
Import {expect, jest, test} from '@jest/globals';
Обратитесь к Началу работы за подробностями о том, как установить Jest с 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.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.clearAllTimers()
jest.getTimerCount()
jest.now()
jest.setSystemTime(now?: number | Date)
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
.
Возвращает объект jest
для создания цепочки вызовов.
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()
Включает автоматическое создание mock-объектов в загрузчике модулей.
For more details on automatic mocking see documentation of automock
configuration option.
Пример:
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
вызовы disableAutomock
будут автоматически перенесены наверх в текущем блоке кода. Если вы хотите явно избежать этого поведения, используйте autoMockOff
.
jest.createMockFromModule(moduleName)
Исходя из имени модуля, используйте систему автоматическую имитацию (automocking), чтобы создать для вас мокн утую версию модуля.
This is useful when you want to create a manual mock that extends the automatic mock's behavior:
- 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
удалить следующие типы данных:
Функция
Creates a new mock function. Новая функция не имеет формальных параметров, и при вызове возвращает undefined
. Эта функция также применима к async
функциям.
Класс
Создает новый класс. Поддерживается интерфейс оригинального класса, все функции и свойства класса будут замоканы.
Объект
Создает новый клонированный объект. Ключи объекта и их значения будут замоканы.
Массив
Создает новый пустой массив, игнорируя оригинал.
Primitives
Создает новое свойство с таким же примитивным значением, как и оригинальное свойство.
Пример:
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: [],
},
});
// создает пустой массив, игнорирую оригинал.
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'));
});