Node.js - Why do we need a home made current date and time function?
Overview
When you need to test your program that is date sensitive and verify your result is what you are expecting, you will need to declare a function that returns the current date.
For example, issuing multiple invoices to the same customer but in different months or years and then ensuring that the aging report for every month is correct. Another example is that you are developing an auto-billing (or auto-debit) system, the testing process can be very confusing without a function that you can manipulate the current date.
Solution
The solution is to declare a function that return current date:
function get_current_date() {
let dt;
if (process.env.TEST) {
// for the test environment.
dt = process.env.TEST_DATE;
}
else {
// for a live environment.
dt = new Date();
}
return new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());
}
You need another function that helps in manipulating the current date in the test environment which looks like the following function:
function set_current_date(dt) {
if (process.env.TEST) {
// for the test environment.
process.env.TEST_DATE = dt;
}
}
Once you have done this, upon generating a new invoice, you will be able to control the current date. For example, you want to test the auto-billing program with the following steps:
- Run the auto-billing process on the 1st of the month.
- Run the auto-billing process on the 2nd of the month.
- Repeat it day after day until the end of the month.
If you are expecting an invoice to be generated at the end of month, you are expecting this program will not generate any invoice before the last day of the month. So, the test case will look like this:
-
Rule: run on the 1st of the month.
- Expect: no invoice will be generated.
-
...(repeat the rules and expectations for each day)...
-
Rule: run on the last day of the month.
- Expect: x invoices and it should be the same as the number of subscribers (or whatever number based on your use case).
Conclusion
Writing a test case for a date sensitive program is challenging because it is difficult to simulate the actual process. So, you need to manipulate the current date.
If your date requires you to handle UTC timezone, it will be definitely more challenging.
Back to #NODEJS blog
Back to #blog listing