如何模拟像 new Date() 这样的构造函数 [英] How to mock a constructor like new Date()

查看:26
本文介绍了如何模拟像 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() 的返回值?

how do I mock the return value of new Date()?

推荐答案

更新:这个答案是 jest <版本 26 请参阅最近玩笑版本的此答案.

Update: this answer is the approach for jest < version 26 see this answer for recent jest versions.

你可以使用 jest.spyOn 模拟像 new Date() 这样的构造函数,如下所示:

You can mock a constructor like new Date() using jest.spyOn as below:

test('mocks a constructor like new Date()', () => {
  console.log('Normal:   ', new Date().getTime())

  const mockDate = new Date(1466424490000)
  const spy = jest
    .spyOn(global, 'Date')
    .mockImplementation(() => mockDate)

  console.log('Mocked:   ', new Date().getTime())
  spy.mockRestore()

  console.log('Restored: ', new Date().getTime())
})

输出如下:

Normal:    1566424897579
Mocked:    1466424490000
Restored:  1566424897608

请参阅 GitHub 上的参考项目.

注意:如果您使用的是 TypeScript 并且会遇到编译错误,Argument of type '() =>日期'不能分配给'() => 类型的参数.细绳'.类型 'Date' 不能分配给类型 'string'.在这种情况下,一种解决方法是使用 mockdate 库,该库可用于在"现在"是.有关详细信息,请参阅这个问题.

Note: If you are using TypeScript and you would encounter a compilation error, Argument of type '() => Date' is not assignable to parameter of type '() => string'. Type 'Date' is not assignable to type 'string'. In this case, a workaround is to use the mockdate library, which can be used to change when "now" is. See this question for more details.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆