Skip to content

Instantly share code, notes, and snippets.

@H6
Created February 6, 2024 21:08
Show Gist options
  • Save H6/6dc5f2df91b89e8007d30e8b4b05ad8b to your computer and use it in GitHub Desktop.
Save H6/6dc5f2df91b89e8007d30e8b4b05ad8b to your computer and use it in GitHub Desktop.
Faking System Time using Jest Fake Timers and Luxon Settings
import { Settings, DateTime } from 'luxon';
import { theFutureIsNow, theFutureIsNowWithLuxon } from './index';
describe("Fake Timer", () => {
describe("Testing with Jest fake timers", () => {
test('theFutureIsNow should return the time in two hours', () => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2021-01-01T00:00:00Z').getTime());
expect(theFutureIsNow()).toEqual(new Date('2021-01-01T02:00:00Z'));
})
})
describe("Testing with Luxon Settings class", () => {
Settings.now = () => new Date('2021-01-01T00:00:00Z').getTime()
test('theFutureIsNowWithLuxon should return the time in two hours', () => {
expect(theFutureIsNowWithLuxon().toISO({ suppressMilliseconds: true })).toEqual('2021-01-01T02:00:00Z');
})
})
})
import { DateTime } from 'luxon'
/**
* Adds two hours to the current time and returns the time.
*/
export function theFutureIsNow() {
const now = new Date();
now.setHours(now.getHours() + 2);
return now;
}
/**
* Adds two hours the the current time retrieved with Luxon and returns the time.
*/
export function theFutureIsNowWithLuxon() {
return DateTime.utc().plus({ hours: 2 });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment