AngularJS - unit tests on a controller that uses moment.js
I am trying to make unit tests for a controller that uses moment.js to handle three week dates. My testing framework is jasmine and my AngularJS version is v1.3.15
Basically I have an init () function that sets them up and I want to check if they are set correctly in the controller.
var myController = this;
myController.init = function () {
myController.currentDate = moment().format('DD-MM-YYYY');
myController.startOfWeek = moment(currentDate).startOf('week').format('DD-MM-YYYY');
myController.endOfWeek = moment(currentDate).endOf('week').format('DD-MM-YYYY');
};
At this point, I'm not sure if this approach is correct and / or if I should check out this stuff here.
Thanks in advance!
source to share
You don't have to pass currentDate
back to the moment creation function. This will highlight the parsing, fall back to the browser implementation (give you a deprecation warning), and fail if the browser locale is not the same as the one you formatted.
Or just call moment()
each time:
myController.currentDate = moment().format('DD-MM-YYYY');
myController.startOfWeek = moment().startOf('week').format('DD-MM-YYYY');
myController.endOfWeek = moment().endOf('week').format('DD-MM-YYYY');
Or, if you like, you can only capture the current time once, then clone that moment for each function.
var now = moment();
myController.currentDate = now.format('DD-MM-YYYY');
myController.startOfWeek = moment(now).startOf('week').format('DD-MM-YYYY');
myController.endOfWeek = moment(now).endOf('week').format('DD-MM-YYYY');
The transition moment to moment creation function will clone it, preventing the change startOf
and endOf
the initial value.
source to share