DEV Community

Julio Lugo
Julio Lugo

Posted on

Test dates-related and time features using date-fns and Jest

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.

Image description

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 = {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

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
})

Enter fullscreen mode Exit fullscreen mode

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')

...
})
Enter fullscreen mode Exit fullscreen mode

And the code

import { isToday } from 'date-fns'

export const getHumanizeDate = (date: string): string => {
  const dateToCheck = new Date(Date.parse(date))

  return isToday(dateToCheck)
Enter fullscreen mode Exit fullscreen mode

Sources:

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay