How to use fake timers in Jest
22 December 2023 (Updated 22 December 2023)
Suppose you have a calculateAge(dateOfBirth: string)
function that takes a date of birth argument in the format DD/MM/YYYY
and returns the age as a number.
To test the function, you can fake the current date in Jest using faker timers:
import { calculateAge } from './dateTimeHelpers'
import { DATE_FORMATS } from '../constants'
describe('dateTimeHelpers', () => {
describe('calculateAge', () => {
const dateOfBirth = '12/07/1993'
beforeEach(() => {
jest.useFakeTimers()
})
it('calculates age correctly when the birthday has passed this year', () => {
jest.setSystemTime(new Date('2023-07-13'))
expect(calculateAge(dateOfBirth, DATE_FORMATS.DAY_MONTH_YEAR)).toBe(30)
})
it('calculates age correctly when the birthday has not yet occurred this year', () => {
jest.setSystemTime(new Date('2023-07-11'))
expect(calculateAge(dateOfBirth, DATE_FORMATS.DAY_MONTH_YEAR)).toBe(29)
})
it('calculates age correctly on the birthday', () => {
jest.setSystemTime(new Date('2023-07-12'))
expect(calculateAge(dateOfBirth, DATE_FORMATS.DAY_MONTH_YEAR)).toBe(30)
})
afterEach(() => {
jest.restoreAllMocks().useRealTimers()
})
})
})
Tagged:
Jest
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment