I have a directive that initializes the Date object several times in several functions. When Unit testing the individual functions I can handle stubbing the date like this:
A straightforward solution would be to create an Angular Dates
service that provides Date
objects for you - it might even just have a single method - Dates.now()
- that just sends back the current date by returning new Date()
. You then use this service whenever something needs to get the current date.
This then allows you to inject a different Dates
service when unit testing, for example one that always returns a specific date of your choice when called, rather than the current time.