Testing Luxon's DateTime object with Jest has been a bit challenging for me as there isn't much documentation available. I am facing issues while trying to instantiate a DateTime object in my Jest test, as it keeps showing up as 'undefined' every time I run the test. Can someone please guide me on how to implement jest.mock() or any other method to successfully mock DateTime in Jest so that I can set a DateTime in my test and have it pass?
To provide some context, the actual DateTime (this.data.ApptDateTime
) is initialized at a different part of the code before setLocalTimeZone()
is called, so it is already in luxon DateTime format. The objective of this portion of the code is to ensure that the date and time are adjusted to the user's current local timezone.
This situation pertains to an Angular project where Jest is being used as the testing framework.
CODE:
import { DateTime } from 'luxon'
setLocalTimeZone() {
const local = DateTime.local()
//the line below results in 'undefined' during my Jest test
this.data.ApptDateTime.setZone(local.zoneName)
}
JEST TEST:
it('should schedule closing with success result', () => {
component.data = new ScheduleClosingCreateModel({
ApptDateTime: DateTime.local(2021, 8, 8, 20, 13, 700),
})
//an exception is thrown due to apptDatetime being undefined
component.setLocalTimeZone()
expect(component.data.ApptDateTime.zoneName).toEqual('America/New_York')
})
The error message received:
TypeError: Cannot read property 'setZone' of undefined