Jestオブジェクト
jest
オブジェクトは、すべてのテストファイル内で自動的にスコープされます。 jest
オブジェクトのメソッドはモックの作成に役立ち、Jestの全体的な動作を制御できます。 import {jest} from '@jest/globals'
を介して明示的にインポートするこ ともできます。
このページの TypeScript の例は、次のように Jest の API を明示的にインポートした場合にのみ動作します。
import {expect, jest, test} from '@jest/globals';
TypeScript で Jest をセットアップする方法の詳細については、Getting Started ガイドを参照してください。
メソッド
- モックモジュール
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)
- モック関数
- 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.getRealSystemTime()
- その他
モックモジュール
jest.disableAutomock()
モジュールローダーの自動モック機能を無効にします。
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');
});
この関数はモックしたい依存関係が、モックが要らないものよりもはるかに少ないシナリオがある場合に便利です。 例えば、"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
オブジェクトを返します。
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()
モジュールローダーで自動モック機能を有効化します。
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
を使用している場合は、enableAutomock
の呼び出しは自動的にコードの先頭で行われます。 この動作を避けるにはautoMockOn
を明示的に使用して下さい。
jest.createMockFromModule(moduleName)
与えられた名前のモジュールに対して自動モック化システムを利用してモック化したモジュールを作成します。
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. 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.
例:
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: [],
},
});
// 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された際に自動モック化されたモジュールのモックを作成します。 factory
と options
はオプションです。 例:
module.exports = () => 'banana';
jest.mock('../banana');
const banana = require('../banana'); // banana will be explicitly mocked.
banana(); // will return 'undefined' because the function is auto-mocked.