How to Mock the Date in Jest Consistently
This post contain affiliate links to Udemy courses, meaning when you click the links and make a purchase, I receive a small commission. I only recommend courses that I believe support the content, and it helps maintain the site.
I am currently working on a project that uses an un-ejected CRA (Create React App) that uses a Material UI Datepicker. The project uses CRACO to extend Webpack setting functionality.
There were some date tests that had been written by another member of the team that worked on all of the devices located in America.
I am based in the UK. They did not run on my device. Tests would fail saying that they were a day behind…
It seems Jest uses the local device Date if it is not mocked. And Jest does not have a simple way of mocking Date. Hard setting the date at the top of the test does not work. Setting the timezone as suggested here does not work 100% of the time…
After over an hour of testing multiple different ‘solutions’, the only thing that I found to work was the Mock Date package. This allows Jest to set timezone for tests.
Once that package is added, set this environment variable in your package.json scripts line:
"scripts": {
"test": "env TZ='UTC' jest",
},
This forces UTC to be the global timezone when testing.
Absolute lifesaver. Drops in and solves the issue. Super easy to set up.
Take a look at the article on testing with Jest and React Testing Library for a basic overview of unit testing.
This is not much of a post, but hopefully it saves the next person some time! If you have a question, send me a message on Twitter @robertmars