本文介绍了如何模拟像New Date()这样的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个依赖于 new Date 的方法来创建一个日期对象,然后对其进行操作。我正在测试操作是否按预期工作,因此我需要将返回的日期与预期日期进行比较。为此,我需要确保 new Date 在测试和被测试的方法中返回相同的值。我该怎么做?

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?

我可以使用提供日期对象的函数创建一个模块,并且可以进行模拟。但这似乎是我代码中不必要的抽象。

I could create a module that can be required with a function that provides a date object and can be mocked. But that seems like an unnecessary abstraction in my code.

要测试的示例函数...

an example function to be tested...

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

如何模拟的返回值new Date()

推荐答案

您可以使用模拟函数覆盖Date构造函数,该函数返回带有日期值的构造Date对象你指定:

You can override Date constructor with an mocked function which returns your a constructed Date object with a date value you specified:

var yourModule = require('./yourModule')

test('Mock Date', () => {
  const mockedDate = new Date(2017, 11, 10)
  const originalDate = Date

  global.Date = jest.fn(() => mockedDate)
  global.Date.setDate = originalDate.setDate

  expect(yourModule.sameTimeTomorrow().getDate()).toEqual(11)
})

您可以在此处测试示例:

You can test the example here: https://repl.it/@miluoshi5/jest-mock-date

这篇关于如何模拟像New Date()这样的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:18