如何在 Jest Test 中模拟 Luxon DateTime obj

问题描述 投票:0回答:2

我还没有找到很多关于如何使用 Jest 测试 Luxon 的 DateTime 对象的文档。我正在努力在 Jest 测试中实例化 DateTime 对象,每次运行它时它都会显示为“未定义”。有人能够演示 jest.mock() 实现或其他一些方法来使 Jest 模拟 DateTime 工作,以便我可以在测试中设置 DateTime 并使其通过吗?

对于上下文,实际的 DateTime (

this.data.ApptDateTime
) 在调用
setLocalTimeZone()
之前在代码中的不同位置设置,因此它已经采用 luxon DateTime 格式。此代码的目的是确保日期和时间位于用户当前的本地时区。

这是一个使用 Jest 作为测试框架的 Angular 项目。

代码:

import { DateTime } from 'luxon'
      
setLocalTimeZone() {
   const local = DateTime.local()

   //line below - comes up undefined in my Jest test 
   this.data.ApptDateTime.setZone(local.zoneName)
        
}

开玩笑测试:

it('should schedule closing with success result', () => {
    component.data = new ScheduleClosingCreateModel({
      ApptDateTime: DateTime.local(2021, 8, 8, 20, 13, 700),
    })

    //exception thrown for apptDatetime being undefined
    component.setLocalTimeZone()

    expect(component.data.ApptDateTime.zoneName).toEqual('America/New_York')
    
})

错误:

TypeError: Cannot read property 'setZone' of undefined

angular typescript unit-testing jestjs luxon
2个回答
0
投票

您要测试的代码正在使用

DateTime.local()
,它返回一个 luxon DateTime 实例,表示当前执行时区中的“现在”。

您可以使用玩笑助手来模拟

DateTime.local()
来控制它返回的值,因此 wheneverwherever 测试运行时可以得到相同的输出(具有给定日期和区域的 DateTime 对象):

import { DateTime } from "luxon";

test("mock DateTime.local()", () => {

  const fakeLocal = DateTime.local(1982, 5, 25, {
    zone: "America/New_York",
  });

  DateTime.local = jest.fn(() => fakeLocal);

  expect(DateTime.local().zoneName).toBe("America/New_York");
});


0
投票

我相信你可以这样做:

import { DateTime, Settings } from 'luxon';

// arrange
const timeTravel = DateTime.local(2021, 6, 1, 23, 0, 0);
Settings.now = () => timeTravel.toMillis();

// act
const actual = somethingThatDependsOnDateTimeNow();
© www.soinside.com 2019 - 2024. All rights reserved.