How can this snippet code be unit tested using jasmine ?
$scope.profileObject = ProfilesSharedObject;
$scope.$watch("profileObject.startDate", function() {
var startDate = $scope.profileObject.startDate._d;
var endDate = $scope.profileObject.endDate._d;
var newStartDate = moment(startDate).format("YYYY-MM-DD");
var newEndDate = moment(endDate).format("YYYY-MM-DD");
$scope.startDate = moment(startDate).format("MM/DD");
$scope.endDate = moment(endDate).format("MM/DD/YYYY");
$scope.getSleepData(newStartDate, newEndDate);
});
where ProfileSharedObject is a angular js service
Watch listeners are evaluated at every digest cycle. Usually that happens automagically, but while unit testing you need to manually trigger it:
it('should update the start date', function() {
// Arrange
ProfileSharedObjectMock.startDate = new Date(2013, 0, 1);
// Act
$scope.$digest();
// Assert
expect($scope.startDate).toEqual(new Date(2013, 0, 1));
});
I've created a Plunker script so you can see the whole test suite working.
来源:https://stackoverflow.com/questions/18839438/unit-testing-watchers-in-angular-js-controller