嘲笑一个在不同环境中无法正常工作的日期

时间:2018-11-29 17:06:50

标签: 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.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 个答案:

答案 0 :(得分:4)

您应该使用jest.spyOn来锁定时间:

db.collection.aggregate(
    {project : {"name" : 1, _id:0, sizeOf : {$size : {
        $filter: {
            input: "$People.Age",
            as: "age",
            cond: { $eq:[$$age, 21] }
        }
    }}}}
)

对于Jest上的日期和时间测试,我编写了一个名为jest-date-mock的模块,它将使日期和时间测试变得简单且可控。

let dateNowSpy;

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

afterAll(() => {
    // Unlock Time
    dateNowSpy.mockRestore();
});