Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock Luxon DateTime obj in Jest Test

I haven't found a lot of documentation on how to test Luxon's DateTime object using Jest. I am struggling to instantiate a DateTime object in my Jest test and it comes up as 'undefined' every time I run it. Would someone be able to demonstrate a jest.mock() implementation or some other way to make Jest mock DateTime work so I can set a DateTime in my test and have it pass?

For context, the actual DateTime (this.data.ApptDateTime) is set in a different place in the code before setLocalTimeZone() gets called so it's already in luxon DateTime format. The purpose of this code is to make sure the date and time is in the user's current local timezone.

This is an Angular project using Jest as the testing framework.

CODE:

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

   //line below - comes up undefined in 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),
    })

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

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

The error: TypeError: Cannot read property 'setZone' of undefined

like image 862
aboukazam Avatar asked Nov 05 '25 03:11

aboukazam


2 Answers

I believe you can do it like this:

import { DateTime, Settings } from 'luxon';

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

// act
const actual = somethingThatDependsOnDateTimeNow();

See this issue for reference.

like image 129
Jannie Theunissen Avatar answered Nov 07 '25 18:11

Jannie Theunissen


The code you want to test is using DateTime.local() which returns a luxon DateTime instance representing "now" in the current execution timezone.

You can mock DateTime.local() with jest helpers to control the value it returns so whenever and wherever the test is run the same output (a DateTime object with a given date and zone) can be expected:

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

like image 28
athmos Avatar answered Nov 07 '25 18:11

athmos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!