【发布时间】: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