85

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

有没有办法真正模拟构造函数的返回值?

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

要测试的示例函数...

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

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

4

12 回答 12

100

自 jest 26 以来,您可以使用支持该方法的“现代”fakeTimers 实现(请参阅此处的文章jest.setSystemTime) 。

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

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

请注意,这'modern'将是 jest 版本 27 的默认实现。

请参阅setSystemTime 此处的文档。

于 2021-01-03T08:51:31.273 回答
91

更新:这个答案是jest < version 26查看最近笑话版本的这个答案的方法。


jest.spyOn您可以使用如下方式模拟像 new Date() 这样的构造函数:

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' is not assignable to parameter of type '() => string'. Type 'Date' is not assignable to type 'string'. 在这种情况下,一种解决方法是使用mockdate库,它可用于更改“现在”的时间。有关更多详细信息,请参阅此问题

于 2019-08-21T22:03:49.327 回答
26

您可以使用 jasmine 的 spyOn(jest 是基于 jasmine 构建的)来模拟 Date 的 getDate 原型,如下所示:

spyOn(Date.prototype, 'setDate').and.returnValue(DATE_TO_TEST_WITH);

SpyOn 也会在它自身之后进行清理,并且仅持续测试范围。

于 2017-03-08T23:08:15.310 回答
11

尽管其他答案解决了这个问题,但我发现它更自然且通常适用于仅模拟 Date 的“无参数构造函数”行为,同时保持 Date 的其他功能不变。例如,当 ISO 日期字符串传递给构造函数时,期望返回此特定日期而不是模拟日期可能是合理的。

test('spies new Date(...params) constructor returning a mock when no args are passed but delegating to real constructor otherwise', () => {
    const DateReal = global.Date;
    const mockDate = new Date("2020-11-01T00:00:00.000Z");

    const spy = jest
        .spyOn(global, 'Date')
        .mockImplementation((...args) => {
            if (args.length) {
                return new DateReal(...args);
            }
            return mockDate;
        })
        
    const dateNow = new Date();

    //no parameter => mocked current Date returned
    console.log(dateNow.toISOString()); //outputs: "2020-11-01T00:00:00.000Z"

    //explicit parameters passed => delegated to the real constructor
    console.log(new Date("2020-11-30").toISOString()); //outputs: "2020-11-30T00:00:00.000Z"
    
    //(the mocked) current Date + 1 month => delegated to the real constructor
    let dateOneMonthFromNow = new Date(dateNow);
    dateOneMonthFromNow.setMonth(dateNow.getMonth() + 1);
    console.log(dateOneMonthFromNow.toISOString()); //outputs: "2020-12-01T00:00:00.000Z"

    spy.mockRestore();
}); 
于 2020-10-24T10:37:56.500 回答
10

您可以使用模拟函数覆盖 Date 构造函数,该函数返回您构造的 Date 对象,其中包含您指定的日期值:

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)
})

您可以在此处测试示例:https ://repl.it/@miluoshi5/jest-mock-date

于 2017-11-21T23:53:46.030 回答
2

您可以将 Date 构造函数替换为始终返回硬编码日期的内容,然后在完成后将其恢复正常。

var _Date = null;

function replaceDate() {
  if (_Date) {
    return
  };

  _Date = Date;

  Object.getOwnPropertyNames(Date).forEach(function(name) { 
    _Date[name] = Date[name] 
  });

  // set Date ctor to always return same date
  Date = function() { return new _Date('2000-01-01T00:00:00.000Z') }

  Object.getOwnPropertyNames(_Date).forEach(function(name) { 
    Date[name] = _Date[name] 
  });  
}

function repairDate() {
  if (_Date === null) {
    return;
  }

  Date = _Date;
  Object.getOwnPropertyNames(_Date).forEach(function(name) { 
    Date[name] = _Date[name] 
  });  

  _Date = null;
}

// test that two dates created at different times return the same timestamp
var t0 = new Date();

// create another one 100ms later
setTimeout(function() {
  var t1 = new Date();

  console.log(t0.getTime(), t1.getTime(), t0.getTime() === t1.getTime());

  // put things back to normal when done
  repairDate();
}, 100);
于 2017-03-09T02:29:17.937 回答
1

如果您有多个日期(在多个测试中或在一个测试中多次),您可能需要执行以下操作:

const OriginalDate = Date;

it('should stub multiple date instances', () => {
  jest.spyOn(global, 'Date');
  const date1: any = new OriginalDate(2021, 1, 18);
  (Date as any).mockImplementationOnce(mockDate(OriginalDate, date1));

  const date2: any = new OriginalDate(2021, 1, 19);
  (Date as any).mockImplementationOnce(mockDate(OriginalDate, date2));

  const actualDate1 = new Date();
  const actualDate2 = new Date();

  expect(actualDate1).toBe(date1);
  expect(actualDate2).toBe(date2);
});

function mockDate(OriginalDate: DateConstructor, date: any): any {
  return (aDate: string) => {
    if (aDate) {
      return new OriginalDate(aDate);
    }
    return date;
  };
}

另请参阅此答案


原答案:

new Date()我刚刚写了一个笑话测试并且能够存根global.Date = () => now

于 2018-08-30T16:20:36.757 回答
1

您可以使用date-faker来模拟 new Date() 或 Date.now() 返回的内容。

import { dateFaker } from 'date-faker'; // var { dateFaker } = require('date-faker');

// will return tomorrow, shift by one unit
dateFaker.add(1, 'day'); 

// shift by several units
dateFaker.add({ year: 1, month: -2, day: 3 });

// set up specific date, accepts Date or time string
dateFaker.set('2019/01/24'); 

dateFaker.reset();
于 2020-03-17T12:40:29.630 回答
1

只需这样做:

it('should mock Date and its methods', () => {
    const mockDate = new Date('14 Oct 1995')
    global.Date = jest.fn().mockImplementation(() => mockDate)
    Date.prototype.setHours = jest.fn().mockImplementation((hours) => hours)
    Date.prototype.getHours = jest.fn().mockReturnValue(1)
}

它对我有用

于 2020-10-29T03:52:21.193 回答
1

就我而言,我必须在测试之前模拟整个 Date 和 'now' 函数:

const mockedData = new Date('2020-11-26T00:00:00.000Z');

jest.spyOn(global, 'Date').mockImplementation(() => mockedData);

Date.now = () => 1606348800;

describe('test', () => {...})

于 2020-11-26T10:06:28.757 回答
0

我正在使用 Typescript,我发现最简单的实现是执行以下操作:

const spy = jest.spyOn(global, 'Date');  // spy on date
const date = spy.mock.instances[0];      // gets the date in string format

然后new Date(date)用于您的测试

于 2020-09-25T16:32:46.850 回答
-3

这就是我现在正在做的事情,它正在工作并且不会弄乱我的方法的签名。

新日期.js

module.exports = function(){
  return new Date();
};

someModule.js

var newDate = require('newDate.js');
module.exports = {
  sameTimeTomorrow: function(){
    var dt = newDate();
        dt.setDate(dt.getDate() + 1);
    return dt;
  }
};

someModule-test.js

jest.dontMock('someModule.js');

describe('someModule', function(){

  it('sameTimeTomorrow', function(){
   var newDate = require('../../_app/util/newDate.js');
       newDate.mockReturnValue(new Date(2015, 02, 13, 09, 15, 40, 123));

   var someModule = require('someModule.js');

   expect(someModule.sameTimeTomorrow().toString()).toBe(new Date(2015, 02, 14, 09, 15, 40, 123).toString());
  });

});
于 2015-02-13T19:59:36.387 回答