Mock a date in Jest

You can use jest.useFakeTimers('modern').setSystemTime(Date) to mock a date and time in your Jest tests.

Example:

javascript
import React                                  from 'react';
import { render, fireEvent, screen, waitFor } from '@testing-library/react';
import { BrowserRouter }                      from 'react-router-dom';
import ThemeSelector                          from '../Components/ThemeSelector';

test('Night mode at 20:00', async () => {
    
    // Setting the 27th December 2020 at 20:00
    jest.useFakeTimers('modern').setSystemTime(new Date(2020, 12, 27, 20));
    
    render(<ThemeSelector/>);
    
    await waitFor(() => expect(document.querySelector('.nightMode')).toBeTruthy());
    
});

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.