代码之家  ›  专栏  ›  技术社区  ›  Emad Dehnavi

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

  •  1
  • Emad Dehnavi  · 技术社区  · 7 年前

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

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

    但在生产环境中,我得到的结果是导致测试失败: Mon Jan 01 2018 01:00:00 GMT+0100 (CET)

    你知道怎么了吗?

    1 回复  |  直到 7 年前
        1
  •  6
  •   Andrey Gordeev    7 年前

    你应该使用 jest.spyOn

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

    日期及日期;在Jest上进行时间测试时,我编写了一个名为 jest-date-mock

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