How to mock a constructor like new Date() Ask Question

How to mock a constructor like new Date() Ask Question

I have a method which depends on new Date to create a date object and then manipulates it. I'm testing that the manipulation works as expected, so I need to compare the returned date with expected date. In order to do that I need to make sure that new Date returns the same value in the test and in the method being tested. How can I do that?

Is there a way to actually mock the return value of a constructor function?

日付オブジェクトを提供し、モック化できる関数を要求するモジュールを作成することもできます。しかし、それは私のコードでは不必要な抽象化のように思えます。

テストする関数の例...

module.exports = {
  sameTimeTomorrow: function(){
    var dt = new Date();
        dt.setDate(dt + 1);
    return dt;
  }
};

の戻り値をモックするにはどうすればよいですかnew Date()?

ベストアンサー1

jest 26以降では、「最新の」fakeTimers実装(記事はこちらをご覧ください) メソッドをサポートしますjest.setSystemTime

beforeAll(() => {
    jest.useFakeTimers('modern');
    jest.setSystemTime(new Date(2020, 3, 1));
});

afterAll(() => {
    jest.useRealTimers();
});

'modern'これはjest バージョン 27 からのデフォルトの実装になることに注意してください。

ドキュメントを参照setSystemTime ここ

おすすめ記事