【问题标题】:Mock a date in jest not working in different environment开玩笑地模拟日期不在不同的环境中工作
【发布时间】:2019-05-01 19:42:16
【问题描述】:

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

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)

知道有什么问题吗?

【问题讨论】:

    标签: javascript node.js unit-testing mocking jestjs


    【解决方案1】:

    你应该使用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
    }); 
    

    【讨论】:

      猜你喜欢
      • 2019-11-08
      • 2017-07-01
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2020-03-05
      • 1970-01-01
      相关资源
      最近更新 更多