How to Test Functions Depending on Date
Understand how to test JavaScript functions that depend on Date by using Jasmine's clock mocking features. This lesson guides you through mocking dates, calculating days difference, and writing effective tests to handle time-based logic in your applications.
When our applications have instances of Date, we need to be able to test that interaction. One such way is using jasmine.clock.
Let’s see an example of a function using Date to calculate how many days ago a date was.
The Date-dependent function
Looking at the daysAgo function logic in src/days-ago.mjs line by line, we see the following:
-
const nowMilliseconds = Date.now();It starts with the current date in milliseconds. That’s how many milliseconds have elapsed since January 1, 1970 UTC.
-
const dateMilliseconds = date.valueOf();This line takes the passed-in date value in milliseconds so that they’re both in comparable units: milliseconds.
-
const agoMilliseconds = nowMilliseconds - dateMilliseconds;This line subtracts
datefromnowand gets the difference in milliseconds. -
const millisecondsInADay = 1000 * 60 * 60 * 24;This line calculates how many milliseconds in a day. There are ...