Luxon: How should I be writing tests for code that depends on Luxon?

Created on 3 May 2018  Â·  5Comments  Â·  Source: moment/luxon

For example lets say I have this function:

import DateTime from 'luxon';

export default function renderDate() {
  return DateTime.local().toFormat('s');
}

And I want to write a test:

import renderDate from 'renderDate';

describe('renderDate', () => {
  beforeEach(() => {
    // Do something to freeze/mock/whatever the time so that it has 4 seconds
  });

  afterEach(() => {
    // Cleanup
  });

  test('gives me the seconds', () => {
    expect(renderDate()).toBe('4');
  });
});

I've tried some of the time mocking libraries I've found, like mockdate with no success. I've also tried overriding various methods on Date, also with no success.

I'm currently running tests with TZ=utc jest.

Also, if there is a better place to ask this question, please let me know.

troubleshooting

Most helpful comment

Luxon allows you to specify the function that provides the current time:

import { Settings, DateTime } from "luxon";

// it's always May 25
Settings.now = () => new Date(2018, 4, 25).valueOf();
DateTime.local().toISO(); //=> "2018-05-25T00:00:00.000-04:00"

Does that answer your question?

All 5 comments

Luxon allows you to specify the function that provides the current time:

import { Settings, DateTime } from "luxon";

// it's always May 25
Settings.now = () => new Date(2018, 4, 25).valueOf();
DateTime.local().toISO(); //=> "2018-05-25T00:00:00.000-04:00"

Does that answer your question?

Turns out a detail of my implementation caused the issue – my renderDate was closer to this:

import DateTime from 'luxon';

const CURRENT_DATE = DateTime.local();

export default function renderDate() {
  return CURRENT_DATE.toFormat('s');
}

That difference meant that the DateTime was being initialized before any code in the test had the chance to mock/override/provide a specific value for the current time.

Anyway, thanks for your help – it was also good to know how the Settings class is expected to be used in the context of tests.

Thanks @icambron for the help 🔥

I think it could be more explicit on the docs !

@icambron Is it possible to mock luxon in one line, like in this article https://medium.com/front-end-weekly/mocking-moment-js-in-jest-a-simple-one-line-solution-61259ffaaa2

I'm trying it but keep receiving a TypeError: Cannot read property 'fromMillis' of undefined when trying to mock fromMillis

jest.mock('luxon', () => () => ({ fromMillis: (date) => `passed date was ${date}` }));

Does this method alter other files too?

I did an Settings.now = () => new Date().valueOf()) just in case at the end of the jest file.

Was this page helpful?
0 / 5 - 0 ratings