【问题标题】:How to Mock Luxon DateTime obj in Jest Test如何在 Jest 测试中模拟 Luxon DateTime obj
【发布时间】:2023-02-12 23:39:17
【问题描述】:

我还没有找到很多关于如何使用 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

【问题讨论】:

  • DateTime 是复杂递归方法的父级。模拟其完整 API 是不切实际的。
  • 我正在努力在 Jest 测试中实例化 DateTime 对象“:你能给我们看一个minimal, reproducible example吗?
  • @jsejcksn 在这里我稍微简化了它以隔离问题..希望它更具可读性
  • 我不知道为什么你的 ApptDateTime 对象没有定义(这似乎与 Luxon 没有任何关系?),但我想指出你的 setZone 调用没有做任何事情。 setZone 不会发生变异,而是返回一个新的 DateTime 实例,你没有对它做任何事情......

标签: angular typescript unit-testing jestjs luxon


【解决方案1】:

您要测试的代码使用 DateTime.local(),它返回表示当前执行时区中“现在”的 luxon DateTime。

您可以使用 jest helpers 模拟 DateTime.local() 来控制它返回的值每当无论何处运行测试可以预期相同的输出:

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

【讨论】:

    猜你喜欢
    • 2020-01-05
    • 2021-10-12
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2018-04-25
    • 2018-12-15
    • 2020-12-24
    相关资源
    最近更新 更多