Javascript 开玩笑地模仿一个不在不同环境下工作的约会

Javascript 开玩笑地模仿一个不在不同环境下工作的约会,javascript,node.js,unit-testing,mocking,jestjs,Javascript,Node.js,Unit Testing,Mocking,Jestjs,所以我试着在我的测试中模拟一个日期,这就是我所做的: const mockDate = new Date('2018-01-01'); const backupDate = Date; beforeEach(() => { (global.Date as any) = jest.fn(() => mockDate); }) afterEach(() => { (global.Date as any) = backupDate; jest.clearAllMock

所以我试着在我的测试中模拟一个日期,这就是我所做的:

const mockDate = new Date('2018-01-01');
const backupDate = Date;

beforeEach(() => {
  (global.Date as any) = jest.fn(() => mockDate);
})

afterEach(() => {
  (global.Date as any) = backupDate;
  jest.clearAllMocks();
});



const backupDate = Date;
(global.Date as any) = jest.fn(() => mockDate);
expect(myModule).toMatchSnapshot();
(global.Date as any) = jest.fn(() => backupDate);
因此,在我的本地应用程序中,此测试运行良好,并且与我的快照相匹配:

exports[`should match with date`] = `
[MockFunction] {
  "calls": Array [
    Array [
      Object {
           "myDate" : "Mon Jan 01 2018 01:00:00 GMT+0100 (Central European Standard Time)"
}]]}
但在生产环境中,我得到的却是导致测试失败的信息:
2018年1月1日周一01:00:00 GMT+0100(CET)

你知道怎么回事吗?

你应该使用works来锁定时间:

let dateNowSpy;

beforeAll(() => {
    // Lock Time
    dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => 1487076708000);
});

afterAll(() => {
    // Unlock Time
    dateNowSpy.mockRestore();
});
对于Jest上的日期和时间测试,我编写了一个名为的模块,它将使日期和时间测试简单且可控

import { advanceBy, advanceTo, clear } from 'jest-date-mock';

test('usage', () => {
  advanceTo(new Date(2018, 5, 27, 0, 0, 0)); // reset to date time.

  const now = Date.now();

  advanceBy(3000); // advance time 3 seconds
  expect(+new Date() - now).toBe(3000);

  advanceBy(-1000); // advance time -1 second
  expect(+new Date() - now).toBe(2000);

  clear();
  Date.now(); // will got current timestamp
});