How to Test Functions Depending on Date
Learn testing functions that depend on the date and time directly, in the browser and Node.js context.
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
date
fromnow
and gets the difference in milliseconds. -
const millisecondsInADay = 1000 * 60 * 60 * 24;
This line calculates how many milliseconds in a day. There are 1,000 milliseconds in a second, 60 seconds in a minute, 60 minutes in an hour, and 24 hours in a day.
-
const daysAgo = agoMilliseconds / millisecondsInADay;
This line divides the milliseconds ago with the milliseconds in a day, getting how many days ago the date was.
-
return Math.round(daysAgo);
This line rounds the
daysAgo
number to the nearest integer because we want to getThis date was 7 days ago
and notThis date was 7.1430499282 days ago
.
Testing the Date-dependent function
Let’s run that using the code playground below and break the test down after.
Get hands-on with 1400+ tech skills courses.