Mock Functions
ただ出力をテストするだけでなく、他のコードから間接的に呼び出された関数の振る舞いを見張ることができるので、モック関数は "スパイ"とも呼ばれます。 jest.fn()関数でモック関数を作成できます。 実装が与えられなければ、モック関数は実行時にundefinedを返します。
メソッド
mockFn.getMockName()mockFn.mock.callsmockFn.mock.resultsmockFn.mock.instancesmockFn.mockClear()mockFn.mockReset()mockFn.mockRestore()mockFn.mockImplementation(fn)mockFn.mockImplementationOnce(fn)mockFn.mockName(value)mockFn.mockReturnThis()mockFn.mockReturnValue(value)mockFn.mockReturnValueOnce(value)mockFn.mockResolvedValue(value)mockFn.mockResolvedValueOnce(value)mockFn.mockRejectedValue(value)mockFn.mockRejectedValueOnce(value)
リファレンス
mockFn.getMockName()
mockFn.mockName(value)を呼び出すと、モック名の文字列を返します。
mockFn.mock.calls
An array containing the call arguments of all calls that have been made to this mock function. Each item in the array is an array of arguments that were passed during the call.
例: f('arg1', 'arg2')とf('arg3', 'arg4')の形で2回呼ばれるモック関数fは次のようなmock.callsの配列を持ちます:
[
['arg1', 'arg2'],
['arg3', 'arg4'],
];
mockFn.mock.results
モック関数に対して行われたすべての呼び出しの結果を含む配列。 Each entry in this array is an object containing a boolean isThrow property, and a value property. isThrow is true if the call terminated due to a throw, or false if the call returned normally. The value property contains the value that was thrown or returned.
For example: A mock function f that has been called three times, returning result1, throwing an error, and then returning result2, would have a mock.results array that looks like this:
[
{
isThrow: false,
value: 'result1',
},
{
isThrow: true,
value: {
/* Error instance */
},
},
{
isThrow: false,
value: 'result2',
},
];
mockFn.mock.instances
new によりモック関数からインスタンス化されたオブジェクトのインスタンス全ての配列。
例: 2回インスタンス化されたモック関数は次のような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.mockClear()
mockFn.mock.calls と mockFn.mock.instancesの配列に格納されている全ての情報をリセットします。
2つのアサーションの間でモックの使用状況をクリーンアップしたいときにしばしば役立ちます。
mockClear は mockFn.mock.calls とmockFn.mock.instancesだけでなくmockFn.mock も置き換えることに注意して下さい。 You should, therefore, avoid assigning mockFn.mock to other variables, temporary or not, to make sure you don't access stale data.
テスト間で自動的にモックをクリアするために clearMocksの設定オプションが利用できます。
mockFn.mockReset()
Does everything that mockFn.mockClear() does, and also removes any mocked return values or implementations.
This is useful when you want to completely reset a mock back to its initial state. (Note that resetting a spy will result in a function with no return value).
mockReset は mockFn.mock.calls とmockFn.mock.instancesだけでなくmockFn.mock も置き換えることに注意して下さい。 You should, therefore, avoid assigning mockFn.mock to other variables, temporary or not, to make sure you don't access stale data.
mockFn.mockRestore()
Does everything that mockFn.mockReset() does, and also restores the original (non-mocked) implementation.
あるテストケースでモック関数を利用して他のテストケースでは本物のモジュールに戻したいときに便利です。
mockFn.mockRestoreはjest.spyOnによって作成されたモックに対してのみ動作することに注意して下さい。 このため手動で jest.fn()を割り当てた場合は自分で復元作業を行わなければならないことに気をつけて下さい。
テスト間で自動的にモックを復元するために restoreMocksの設定オプションが利用できます。
mockFn.mockImplementation(fn)
モックの実装として使用される関数を受け取ります。 モック自体はそれ自身から出てきたインスタンスと中に与えられた全てのコールをいまだ記録しています - 違いはモックがコールされたときに実装された関数も実行されることです。
注意: jest.fn(implementation) は jest.fn().mockImplementation(implementation) の省略形です。
例:
const mockFn = jest.fn().mockImplementation(scalar => 42 + scalar);
// or: jest.fn(scalar => 42 + scalar);
const a = mockFn(0);
const b = mockFn(1);
a === 42; // true
b === 43; // true
mockFn.mock.calls[0][0] === 0; // true
mockFn.mock.calls[1][0] === 1; // true
mockImplementation はクラスのコンストラクタをモックするのにも使用できます。
// SomeClass.js
module.exports = class SomeClass {
m(a, b) {}
};
// OtherModule.test.js
jest.mock('./SomeClass'); // this happens automatically with automocking
const SomeClass = require('./SomeClass');
const mMock = jest.fn();
SomeClass.mockImplementation(() => {
return {
m: mMock,
};
});
const some = new SomeClass();
some.m('a', 'b');
console.log('Calls to m: ', mMock.mock.calls);
mockFn.mockImplementationOnce(fn)
Accepts a function that will be used as an implementation of the mock for one call to the mocked function. Can be chained so that multiple function calls produce different results.
const myMockFn = jest
.fn()
.mockImplementationOnce(cb => cb(null, true))
.mockImplementationOnce(cb => cb(null, false));
myMockFn((err, val) => console.log(val)); // true
myMockFn((err, val) => console.log(val)); // false
モック関数がmockImplementationOnceによって定義された実装が全て使い切った時は、 呼び出された場合にjest.fn(() => defaultValue) または .mockImplementation(() => defaultValue)によって設定されたデフォルトの実装を実行します。
const myMockFn = jest
.fn(() => 'default')
.mockImplementationOnce(() => 'first call')
.mockImplementationOnce(() => 'second call');
// 'first call', 'second call', 'default', 'default'
console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
mockFn.mockName(value)
どのモック関数が参照されているのかを示すために、"jest.fn()"の代わりにテスト結果で出力される文字列を引数に取ります。
例:
const mockFn = jest.fn().mockName('mockedFunction');
// mockFn();
expect(mockFn).toHaveBeenCalled();
は以下のエラーを出力します:
expect(mockedFunction).toHaveBeenCalled()
Expected mock function "mockedFunction" to have been called, but it was not called.
mockFn.mockReturnThis()
下記の関数の糖衣関数です。
jest.fn(function () {
return this;
});
mockFn.mockReturnValue(value)
モック関数が呼ばれるたびに返す値を受け取ります。
const mock = jest.fn();
mock.mockReturnValue(42);
mock(); // 42
mock.mockReturnValue(43);
mock(); // 43
mockFn.mockReturnValueOnce(value)
モック関数を1回呼び出したときに返す値を受け取ります。 次のモック関数へのコールが異なる値を返せるようチェーンすることができます。 使用できる mockReturnValueOnceの値が無い場合は、 mockReturnValueで設定された値を返します。
const myMockFn = jest
.fn()
.mockReturnValue('default')
.mockReturnValueOnce('first call')
.mockReturnValueOnce('second call');
// 'first call', 'second call', 'default', 'default'
console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
mockFn.mockResolvedValue(value)
下記の関数の糖衣関数です。
jest.fn().mockImplementation(() => Promise.resolve(value));
次のように async テスト内で sync 関数をモックするのに便利です。
test('async test', async () => {
const asyncMock = jest.fn().mockResolvedValue(43);
await asyncMock(); // 43
});
mockFn.mockResolvedValueOnce(value)
下記の関数の糖衣関数です。
jest.fn().mockImplementationOnce(() => Promise.resolve(value));
複数の async 呼び出しを異なる値で解決させるのに便利です。
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)
下記の関数の糖衣関数です。
jest.fn().mockImplementation(() => Promise.reject(value));
常に reject する async モック関数を作るのに便利です。
test('async test', async () => {
const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));
await asyncMock(); // throws "Async error"
});
mockFn.mockRejectedValueOnce(value)
下記の関数の糖衣関数です。
jest.fn().mockImplementationOnce(() => Promise.reject(value));
使用例
test('async test', async () => {
const asyncMock = jest
.fn()
.mockResolvedValueOnce('first call')
.mockRejectedValueOnce(new Error('Async error'));
await asyncMock(); // first call
await asyncMock(); // throws "Async error"
});