In one of my side projects in Node, I wanted to test if the object with the date is formatted correctly as a Markdown entry. The setup of the test was the easiest part. However, comparing the outcome of the formatted Date object wasn’t so convenient because of the timezone. Because I live in the Europe/Warsaw timezone, I experience an offset relative to UTC.

Consider this test scenario:

test('it should parse link to valid markdown entry with title and tags', () => {
    const link = {
        url: 'https://szymonkrajewski.pl',
        title: "Szymon Krajewski's Blog",
        tags: ['blog', 'personal'],
        createdAt: new Date('2021-01-01T15:00:00Z')
    };

    expect(toMarkdown(link)).toBe("- 2021-01-01 15:00 # https://szymonkrajewski.pl # Szymon Krajewski's Blog @blog @personal");
});

After running this test case in jest I got this result:

expect(received).toBe(expected) // Object.is equality

Expected: "- 2021-01-01 15:00 # https://szymonkrajewski.pl # Szymon Krajewski's Blog @blog @personal"
Received: "- 2021-01-01 16:00 # https://szymonkrajewski.pl # Szymon Krajewski's Blog @blog @personal"

It’s a bit silly to arrange 15:00 but expect the 16:00. However, I found that setting the timezone for tests is an excellent way to get deterministic results regardless of the local timezone. Just invoke tests with environment variable TZ=utc, e.g. TZ=utc jest.

I also provide a change to package.json file to be able to run npm test with proper timezone.

"scripts": {
    "test": "TZ=utc jest",
}

The test scenario comes from my side project bkmrx.