Unit testing watchers in angular js controller

筅森魡賤 提交于 2019-12-22 09:15:59

问题


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


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!