开玩笑的打字稿-模拟日期构造函数 [英] jest typescript - Mock Date constructor

查看:104
本文介绍了开玩笑的打字稿-模拟日期构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟new Date()以返回特定日期.以下代码:

I'm trying to mock new Date() to return a specific date. The following code:

const now = new Date()
jest.spyOn(global, 'Date').mockImplementation(() => now)

出现编译错误:Argument of type '() => Date' is not assignable to parameter of type '() => string'. Type 'Date' is not assignable to type 'string'.

我认为原因是开玩笑认为我正在尝试模拟Date()而不是new Date().实际上,Date()返回一个字符串.我该如何解决这个问题?

I think the reason is that jest thinks I'm trying to mock Date() instead of new Date(). Indeed, Date() returns a string. How can I solve this issue?

推荐答案

一种解决方法是使用 mockdate 库,可以在"now"为现时进行更改.

A workaround is to use the mockdate library, which can be used to change when "now" is.

const MockDate = require('mockdate');

test('Mock Date to change when "now" is', () => {
  console.log('Normal:   ', new Date().getTime());

  MockDate.set(new Date(1466424490000));

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

  MockDate.reset();

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

测试结果如下:

$ npm run test
> jest

 PASS  src/test.ts
  ✓ Mock Date to change when "now" is (8ms)

  console.log src/test.ts:4
    Normal:    1585505136315

  console.log src/test.ts:8
    Mocked:    1466424490000

  console.log src/test.ts:12
    Restored:  1585505136322

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.804s

请参见参考项目,网址为GitHub .

这篇关于开玩笑的打字稿-模拟日期构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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