Test-Driven Development: 11- Testing the ReturnDate
Mosh shows how to measure the difference of two dates to test current time. I wonder if there are other ways to test current time, then I found jest.useFakeTimers(‘modern’) and jest.setSystemTime() but I don’t know why it breaks my test.
Does anyone know how to work with these two helpers?
If I add them after the assertion, the test will pass
it('should set dateReturned if input is valid', async () => {
await exec()
const rentalInDb = await Rental.findById(rental._id)
const diff = new Date() - rentalInDb.dateReturned
expect(diff).toBeLessThan(10 * 1000)
jest.useFakeTimers('modern')
jest.setSystemTime(new Date('20 Aug 2020 00:12:00 GMT').getTime())
console.log(rentalInDb.dateReturned)
console.log(new Date())
jest.useRealTimers()
}, 60000)
If I add them in the beginning of the assertion, the test will fail
it('should set dateReturned if input is valid', async () => {
jest.useFakeTimers('modern') // moved to the start of the test
jest.setSystemTime(new Date('20 Aug 2020 00:12:00 GMT').getTime()) // moved to the start of the test
await exec()
const rentalInDb = await Rental.findById(rental._id)
const diff = new Date() - rentalInDb.dateReturned
expect(diff).toBeLessThan(10 * 1000)
console.log(rentalInDb.dateReturned)
console.log(new Date())
jest.useRealTimers()
}, 60000)
error message
● /api/returns › should set dateReturned if input is valid
thrown: "Exceeded timeout of 5000 ms for a hook.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
49 | })
50 |
> 51 | afterEach(async () => {
| ^
52 | await Rental.remove({})
53 | await server.close()
54 | })
at tests/integration/return.test.js:51:3
at Object.<anonymous> (tests/integration/return.test.js:6:1)
at runMicrotasks (<anonymous>)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:387:19)