Search code examples
reactjsunit-testingjestjsluxon

Jest unit test with Luxon: how do I mock .setZone('local')


I have a very simple date component:

import { DateTime } from 'luxon';
export const SimpleDateCell = ({ item, itemKey }) => {
    const isoDateString = item[itemKey];

    if (!isoDateString) {
        return null;
    }

    const formattedDate = DateTime
        .fromISO(isoDateString, { zone: 'utc' })
        .setZone('local')
        .toLocaleString(DateTime.DATETIME_MED);

    return (
        <time dateTime={isoDateString} title={isoDateString}>
            {formattedDate}
        </time>
    ); };

And I was testing it locally with simply:

import React from 'react'; 
import SimpleDateCell from './SimpleDateCell'; 
import { DateTime, Settings } from 'luxon';
import renderer from 'react-test-renderer';

const testData = {
    companyName: 'test company',
    tenantId: 'ai/prod/00DA0000000XoMwMAK',
    // this will be different on different servers when .setZone('local')
    createdDate: '2019-02-13T15:53:00', };

describe('SimpleDateCell', () => {
    it('should match the snapshot', () => {


        const tree = renderer
            .create(
                <SimpleDateCell item={testData} itemKey="createdDate" />
            ).toJSON();
        expect(tree).toMatchSnapshot();
    });  });

The problem is the unit test has to be run in the same timezone as I make the snapshot. So our CI server is rejecting this.

Is there a way to make this pass in any timezone? Maybe mock the setZone('local') response? Any CI experts out there use luxon?

Thank you!


Solution

  • Settings.defaultZone should work. Just in case I highlight: it affects all methods say DateTime.local(). Somebody was already confused by that.

    As an alternative you may mock native Date with timezone-mock or timezoned-date that I believe should also help. And that approach would be more consistent if for any reason some part of your code works with native Date rather luxon's DateTime.