...

/

How to Test Functions Depending on Date

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 from now and gets the difference in milliseconds. ...

Access this course and 1400+ top-rated courses and projects.