Appearance
Time Mocking in Testing
In the UI, we often have time-dependent components such as date selection, displaying date and other time-related logics. Writing unit tests for these components can be challenging since any usage of new Date() would change on each run of the tests. For cases like this, we must mock or freeze the time, which most testing libraries support:
jest.useFakeTimers()
In Jest, we can call useFakeTimers() and setSystemTime() to set the time for the test we are running. For example: below, we freeze the time so that the test can be run consistently.
js
describe("Display Current Time", () => {
beforeAll(() => {
// Use fake timers to mock time-based functions
jest.useFakeTimers();
jest.setSystemTime(new Date('20 Aug 2020 00:00:00 GMT').getTime());
});
afterAll(() => {
// Restore the real timers after tests
jest.useRealTimers();
});
test("should display the current date", () => {
// Call the function that displays the current time
displayCurrentTime();
// Expect the current date to be displayed
expect(document.getElementById("date").textContent).toBe("Thu Aug 20 2020");
})
});