So, one of the issues I was wondering when I started working with Jest was: "How can I test dates and times?" and I felt curious so I started Googling it. At the very beginning, my findings were zero to none and I felt quite down with it, so I decided to experiment on my own... Total failure again.
However, after hours of suffering and reading a bunch of random blogs across the web, I found a simple and straightforward way to achieve this. It starts simply with configuring a fixed TZ for all tests.
// In your jest.config.js
process.env.TZ = 'GMT'
module.exports = {
// ...
}
Then, in your .spec
file, you need to alter your global Date
object and define a jest function for the built-in now function, as follows:
const RealNow = Date.now
beforeAll(() => {
global.Date.now = jest.fn(() => new Date('2019-04-07T10:20:30Z').getTime())
})
afterAll(() => {
global.Date.now = RealNow
})
Once you have it up and running, you can create a very simple test to make sure everything is alright
it ('should show time', () => {
expect(getHumanizeDate('2000/01/03')).toEqual('today')
...
})
And the code
import { isToday } from 'date-fns'
export const getHumanizeDate = (date: string): string => {
const dateToCheck = new Date(Date.parse(date))
return isToday(dateToCheck)
Sources:
Top comments (0)