はじめに
TypeScriptで開発を行う際、テストツールとしてJestを利用しました。
その時のモック化したコードを備忘録としてまとめてみました。
Math.randomとDate.getMonthのモック化を例に紹介します。
環境
node: 16.4.2
ts-node: 10.4.0
typescript: 4.5.5
@types/jest: 27.4.0
jest: 26.6.3
ts-jest: 26.5.6
サンプルコード
sampleMethod.ts
export default class sampleMethod {
public getRandomNumber(): number {
return Math.random()
}
public getMonth(): number {
return new Date().getMonth()
}
}
以下はモックを使う前のテストコード
sampleMethod.test.ts
import sampleMethod from './sampleMethod';
describe('spyOn', () => {
const SampleMethod = new sampleMethod;
// ランダム関数が偶然0を返してくれないとテストに通らない
test(`Math.random`, function () {
const resultNumber = SampleMethod.getRandomNumber();
expect(resultNumber).toBe(0);
});
// 1月にテストした時にしかテストを通らない
test(`Date.getMonth`, function () {
const resultMonth = SampleMethod.getMonth();
expect(resultMonth).toBe(0);
});
})
モック化する
Math.random
- Math.randomが、必ず0を返すモック
初期化してあげないと、意図しないテストに影響することも
jest.spyOn(global.Math, 'random').mockReturnValue(0);
global.Math.random = jest.fn(() => 0);
global.Math.random = jest.fn().mockReturnValue(0);
- Math.randomが、一度だけ、必ず0を返すモック
2回目の呼び出し時は、ランダムに0以上1未満の数字が返ってくる
jest.spyOn(global.Math, 'random').mockReturnValueOnce(0);
global.Math.random = jest.fn().mockReturnValueOnce(0);
Date.getMonth
- Dateオブジェクト全体のモック化
getMonth以外にも、getDayやgetHoursなどのメソッドもモック化された値を返す
const mockDate = new Date('2022-01-01T01:00:00');
jest.spyOn(global, 'Date').mockImplementation(() => mockDate as unknown as string);
- getMonthメソッドのみのモック化
探してみましたが、わかりませんでした。
もし、わかる方がいらっしゃれば教えてください。
jest.spyOn(global.Date.prototype, 'getMonth').mockReturnValue(0);
Math.random同様に、他の記法でもモック化できる。