メインコンテンツへスキップ
Version: Next

モック関数

ただ出力をテストするだけでなく、他のコードから間接的に呼び出された関数の振る舞いを見張ることができるので、モック関数は "スパイ"とも呼ばれます。 jest.fn()関数でモック関数を作成できます。 実装が与えられなければ、モック関数は実行時にundefinedを返します。

info

このページの TypeScript の例は、次のように Jest の API を明示的にインポートした場合にのみ動作します。

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

TypeScript で Jest をセットアップする方法の詳細については、Getting Started ガイドを参照してください。

メソッド


リファレンス

mockFn.getMockName()

Returns the mock name string set by calling .mockName().

mockFn.mock.calls

モック関数に行われた全てのコールを含む配列を返します。 配列の個々の要素は、コールに渡された引数の配列です。

例: f('arg1', 'arg2')f('arg3', 'arg4')の形で2回呼ばれるモック関数fは次のようなmock.callsの配列を持ちます:

[
['arg1', 'arg2'],
['arg3', 'arg4'],
];

mockFn.mock.results

モック関数に対して行われたすべての呼び出しの結果を含む配列。 この配列の各要素は、 タイプ プロパティと プロパティを持つオブジェクトです。 type は以下のいずれかになります:

  • 'return' - 正常終了したコールを示します。
  • 'throw' - 値を返して呼び出しが完了したことを示します。
  • 'incomplete' - 呼び出しがまだ完了していないことを示します。 これは、モック関数自体の中から結果をテストする場合や、モック関数によって呼び出された関数内からの結果をテストする場合に発生します。

value プロパティには、スローまたは返された値が含まれています。 valuetype === 'incomplete' の場合は undefined です。

new によりモック関数からインスタンス化されたオブジェクトのインスタンス全ての配列。

[
{
type: 'return',
value: 'result1',
},
{
type: 'throw',
value: {
/* Error instance */
},
},
{
type: 'return',
value: 'result2',
},
];

mockFn.mock.instances

例: 2回インスタンス化されたモック関数は次のようなmock.instances配列を持ちます:

mockFn.mock.callsmockFn.mock.instancesの配列に格納されている全ての情報をリセットします。

const mockFn = jest.fn();

const a = new mockFn();
const b = new mockFn();

mockFn.mock.instances[0] === a; // true
mockFn.mock.instances[1] === b; // true

mockFn.mock.contexts

An array that contains the contexts for all calls of the mock function.

A context is the this value that a function receives when called. The context can be set using Function.prototype.bind, Function.prototype.call or Function.prototype.apply.

例:

const mockFn = jest.fn();

const boundMockFn = mockFn.bind(thisContext0);
boundMockFn('a', 'b');
mockFn.call(thisContext1, 'a', 'b');
mockFn.apply(thisContext2, ['a', 'b']);

mockFn.mock.contexts[0] === thisContext0; // true
mockFn.mock.contexts[1] === thisContext1; // true
mockFn.mock.contexts[2] === thisContext2; // true

mockFn.mock.lastCall

An array containing the call arguments of the last call that was made to this mock function. If the function was not called, it will return undefined.

For example: A mock function f that has been called twice, with the arguments f('arg1', 'arg2'), and then with the arguments f('arg3', 'arg4'), would have a mock.lastCall array that looks like this:

['arg3', 'arg4'];

mockFn.mockClear()

Clears all information stored in the mockFn.mock.calls, mockFn.mock.instances, mockFn.mock.contexts and mockFn.mock.results arrays. Often this is useful when you want to clean up a mocks usage data between two assertions.

The clearMocks configuration option is available to clear mocks automatically before each tests.

caution

Beware that mockFn.mockClear() will replace mockFn.mock, not just reset the values of its properties! You should, therefore, avoid assigning mockFn.mock to other variables, temporary or not, to make sure you don't access stale data.

mockFn.mockReset()

Does everything that mockFn.mockClear() does, and also replaces the mock implementation with an empty function, returning undefined.

The resetMocks configuration option is available to reset mocks automatically before each test.

mockFn.mockRestore()

Does everything that mockFn.mockReset() does, and also restores the original (non-mocked) implementation.

あるテストケースでモック関数を利用して他のテストケースでは本物のモジュールに戻したいときに便利です。

The restoreMocks configuration option is available to restore mocks automatically before each test.

info

mockFn.mockRestore() only works when the mock was created with jest.spyOn(). このため手動で jest.fn()を割り当てた場合は自分で復元作業を行わなければならないことに気をつけて下さい。

mockFn.mockImplementation(fn)

モックの実装として使用される関数を受け取ります。 モック自体はそれ自身から出てきたインスタンスと中に与えられた全てのコールをいまだ記録しています - 違いはモックがコールされたときに実装された関数も実行されることです。

tip

jest.fn(implementation) is a shorthand for jest.fn().mockImplementation(implementation).

const mockFn = jest.fn(scalar => 42 + scalar);

mockFn(0); // 42
mockFn(1); // 43

mockFn.mockImplementation(scalar => 36 + scalar);

mockFn(2); // 38
mockFn(3); // 39

.mockImplementation() can also be used to mock class constructors:

SomeClass.js
module.exports = class SomeClass {
method(a, b) {}
};
SomeClass.test.js
const SomeClass = require('./SomeClass');

jest.mock('./SomeClass'); // this happens automatically with automocking

const mockMethod = jest.fn();
SomeClass.mockImplementation(() => {
return {
method: mockMethod,
};
});

const some = new SomeClass();
some.method('a', 'b');

console.log('Calls to method:', mockMethod.mock.calls);

mockFn.mockImplementationOnce(fn)

モック関数への1回のコールに対する実装として使用される関数を受け取ります。 関数への複数回のコールが異なる結果を返せるよう、チェーンすることができます。

const mockFn = jest
.fn()
.mockImplementationOnce(cb => cb(null, true))
.mockImplementationOnce(cb => cb(null, false));

mockFn((err, val) => console.log(val)); // true
mockFn((err, val) => console.log(val)); // false

When the mocked function runs out of implementations defined with .mockImplementationOnce(), it will execute the default implementation set with jest.fn(() => defaultValue) or .mockImplementation(() => defaultValue) if they were called:

const mockFn = jest
.fn(() => 'default')
.mockImplementationOnce(() => 'first call')
.mockImplementationOnce(() => 'second call');

mockFn(); // 'first call'
mockFn(); // 'second call'
mockFn(); // 'default'
mockFn(); // 'default'

mockFn.mockName(name)

Accepts a string to use in test result output in place of 'jest.fn()' to indicate which mock function is being referenced.

例:

const mockFn = jest.fn().mockName('mockedFunction');

// mockFn();
expect(mockFn).toHaveBeenCalled();

下記の関数の糖衣関数です。

expect(mockedFunction).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls: 0

mockFn.mockReturnThis()

Shorthand for:

jest.fn(function () {
return this;
});

mockFn.mockReturnValue(value)

Shorthand for:

jest.fn().mockImplementation(() => value);

たとえば、あるモック関数 f が3回呼ばれた時、'result1' が返り、エラーが発生し、'result2' が返った場合、mock.returnValues 配列は次のような値になります。

const mock = jest.fn();

mock.mockReturnValue(42);
mock(); // 42

mock.mockReturnValue(43);
mock(); // 43

mockFn.mockReturnValueOnce(value)

Shorthand for:

jest.fn().mockImplementationOnce(() => value);

モック関数を1回呼び出したときに返す値を受け取ります。 次のモック関数へのコールが異なる値を返せるようチェーンすることができます。 使用できる mockReturnValueOnceの値が無い場合は、 mockReturnValueで設定された値を返します。

const mockFn = jest
.fn()
.mockReturnValue('default')
.mockReturnValueOnce('first call')
.mockReturnValueOnce('second call');

mockFn(); // 'first call'
mockFn(); // 'second call'
mockFn(); // 'default'
mockFn(); // 'default'

mockFn.mockResolvedValue(value)

Shorthand for:

jest.fn().mockImplementation(() => Promise.resolve(value));

下記の関数の糖衣関数です。

test('async test', async () => {
const asyncMock = jest.fn().mockResolvedValue(43);

await asyncMock(); // 43
});

mockFn.mockResolvedValueOnce(value)

Shorthand for:

jest.fn().mockImplementationOnce(() => Promise.resolve(value));

下記の関数の糖衣関数です。

test('async test', async () => {
const asyncMock = jest
.fn()
.mockResolvedValue('default')
.mockResolvedValueOnce('first call')
.mockResolvedValueOnce('second call');

await asyncMock(); // 'first call'
await asyncMock(); // 'second call'
await asyncMock(); // 'default'
await asyncMock(); // 'default'
});

mockFn.mockRejectedValue(value)

Shorthand for:

jest.fn().mockImplementation(() => Promise.reject(value));

下記の関数の糖衣関数です。

test('async test', async () => {
const asyncMock = jest
.fn()
.mockRejectedValue(new Error('Async error message'));

await asyncMock(); // throws 'Async error message'
});

mockFn.mockRejectedValueOnce(value)

Shorthand for:

jest.fn().mockImplementationOnce(() => Promise.reject(value));

Useful together with .mockResolvedValueOnce() or to reject with different exceptions over multiple async calls:

test('async test', async () => {
const asyncMock = jest
.fn()
.mockResolvedValueOnce('first call')
.mockRejectedValueOnce(new Error('Async error message'));

await asyncMock(); // 'first call'
await asyncMock(); // throws 'Async error message'
});

mockFn.withImplementation(fn, callback)

Accepts a function which should be temporarily used as the implementation of the mock while the callback is being executed.

test('test', () => {
const mock = jest.fn(() => 'outside callback');

mock.withImplementation(
() => 'inside callback',
() => {
mock(); // 'inside callback'
},
);

mock(); // 'outside callback'
});

mockFn.withImplementation can be used regardless of whether or not the callback is asynchronous (returns a thenable). If the callback is asynchronous a promise will be returned. Awaiting the promise will await the callback and reset the implementation.

test('async test', async () => {
const mock = jest.fn(() => 'outside callback');

// We await this call since the callback is async
await mock.withImplementation(
() => 'inside callback',
async () => {
mock(); // 'inside callback'
},
);

mock(); // 'outside callback'
});

Replaced Properties

replacedProperty.replaceValue(value)

Changes the value of already replaced property. This is useful when you want to replace property and then adjust the value in specific tests. As an alternative, you can call jest.replaceProperty() multiple times on same property.

replacedProperty.restore()

Restores object's property to the original value.

Beware that replacedProperty.restore() only works when the property value was replaced with jest.replaceProperty().

The restoreMocks configuration option is available to restore replaced properties automatically before each test.

TypeScript Usage

info

このページの TypeScript の例は、次のように Jest の API を明示的にインポートした場合にのみ動作します。

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

TypeScript で Jest をセットアップする方法の詳細については、Getting Started ガイドを参照してください。

jest.fn(implementation?)

Correct mock typings will be inferred if implementation is passed to jest.fn(). There are many use cases where the implementation is omitted. To ensure type safety you may pass a generic type argument (also see the examples above for more reference):

import {expect, jest, test} from '@jest/globals';
import type add from './add';
import calculate from './calc';

test('calculate calls add', () => {
// Create a new mock that can be used in place of `add`.
const mockAdd = jest.fn<typeof add>();

// `.mockImplementation()` now can infer that `a` and `b` are `number`
// and that the returned value is a `number`.
mockAdd.mockImplementation((a, b) => {
// Yes, this mock is still adding two numbers but imagine this
// was a complex function we are mocking.
return a + b;
});

// `mockAdd` is properly typed and therefore accepted by anything
// requiring `add`.
calculate(mockAdd, 1, 2);

expect(mockAdd).toHaveBeenCalledTimes(1);
expect(mockAdd).toHaveBeenCalledWith(1, 2);
});

jest.Mock<T>

Constructs the type of a mock function, e.g. the return type of jest.fn(). It can be useful if you have to defined a recursive mock function:

import {jest} from '@jest/globals';

const sumRecursively: jest.Mock<(value: number) => number> = jest.fn(value => {
if (value === 0) {
return 0;
} else {
return value + fn(value - 1);
}
});

jest.Mocked<Source>

The jest.Mocked<Source> utility type returns the Source type wrapped with type definitions of Jest mock function.

import {expect, jest, test} from '@jest/globals';
import type {fetch} from 'node-fetch';

jest.mock('node-fetch');

let mockedFetch: jest.Mocked<typeof fetch>;

afterEach(() => {
mockedFetch.mockClear();
});

test('makes correct call', () => {
mockedFetch = getMockedFetch();
// ...
});

test('returns correct data', () => {
mockedFetch = getMockedFetch();
// ...
});

Types of classes, functions or objects can be passed as type argument to jest.Mocked<Source>. If you prefer to constrain the input type, use: jest.MockedClass<Source>, jest.MockedFunction<Source> or jest.MockedObject<Source>.

jest.Replaced<Source>

The jest.Replaced<Source> utility type returns the Source type wrapped with type definitions of Jest replaced property.

src/utils.ts
export function isLocalhost(): boolean {
return process.env['HOSTNAME'] === 'localhost';
}
src/__tests__/utils.test.ts
import {afterEach, expect, it, jest} from '@jest/globals';
import {isLocalhost} from '../utils';

let replacedEnv: jest.Replaced<typeof process.env> | undefined = undefined;

afterEach(() => {
replacedEnv?.restore();
});

it('isLocalhost should detect localhost environment', () => {
replacedEnv = jest.replaceProperty(process, 'env', {HOSTNAME: 'localhost'});

expect(isLocalhost()).toBe(true);
});

it('isLocalhost should detect non-localhost environment', () => {
replacedEnv = jest.replaceProperty(process, 'env', {HOSTNAME: 'example.com'});

expect(isLocalhost()).toBe(false);
});

jest.mocked(source, options?)

The mocked() helper method wraps types of the source object and its deep nested members with type definitions of Jest mock function. You can pass {shallow: true} as the options argument to disable the deeply mocked behavior.

Returns the source object.

song.ts
export const song = {
one: {
more: {
time: (t: number) => {
return t;
},
},
},
};
song.test.ts
import {expect, jest, test} from '@jest/globals';
import {song} from './song';

jest.mock('./song');
jest.spyOn(console, 'log');

const mockedSong = jest.mocked(song);
// or through `jest.Mocked<Source>`
// const mockedSong = song as jest.Mocked<typeof song>;

test('deep method is typed correctly', () => {
mockedSong.one.more.time.mockReturnValue(12);

expect(mockedSong.one.more.time(10)).toBe(12);
expect(mockedSong.one.more.time.mock.calls).toHaveLength(1);
});

test('direct usage', () => {
jest.mocked(console.log).mockImplementation(() => {
return;
});

console.log('one more time');

expect(jest.mocked(console.log).mock.calls).toHaveLength(1);
});

jest.Spied<Source>

Constructs the type of a spied class or function (i.e. the return type of jest.spyOn()).

__utils__/setDateNow.ts
import {jest} from '@jest/globals';

export function setDateNow(now: number): jest.Spied<typeof Date.now> {
return jest.spyOn(Date, 'now').mockReturnValue(now);
}
import {afterEach, expect, type jest, test} from '@jest/globals';
import {setDateNow} from './__utils__/setDateNow';

let spiedDateNow: jest.Spied<typeof Date.now> | undefined = undefined;

afterEach(() => {
spiedDateNow?.mockReset();
});

test('renders correctly with a given date', () => {
spiedDateNow = setDateNow(1_482_363_367_071);
// ...

expect(spiedDateNow).toHaveBeenCalledTimes(1);
});

Types of a class or function can be passed as type argument to jest.Spied<Source>. If you prefer to constrain the input type, use: jest.SpiedClass<Source> or jest.SpiedFunction<Source>.

Use jest.SpiedGetter<Source> or jest.SpiedSetter<Source> to create the type of a spied getter or setter respectively.