在测试中执行$ watch,angularjs

时间:2014-10-22 14:49:06

标签: angularjs karma-runner

我的控制器中有这个代码:

angular.module('clientApp')
  .controller('UserSettingsAccountCtrl', function ($scope, userFactory) {

    $scope.$watch(function() {
      return userFactory.getUser();
    }, function(value) {
      $scope.user = value;
      console.log($scope.user) //defined when I add scope.$digest() in my test
      }
    });

    console.log($scope.user) //undefined
});

我的控制器实例化时执行。但在我的测试中,它不是。我得到用户未定义。

beforeEach(inject(function ($controller, $rootScope, userFactory) {
    scope = $rootScope.$new();
    var mockUser = {
      userId: 1,
      name: 'Per',
      premium:{
        active:false,
        freeTrial:{
          expired:{
            value:false
          }
        }
      }
    };
    userFactory.setUser(mockUser);
    console.log(userFactory.getUser()); //User is returned
    UserSettingsAccountCtrl = $controller('UserSettingsAccountCtrl', {
      $scope: scope,
    });
  }));

  it('should be ok to start a trial if the trial has not expired and the user is not a premium', function(){
    console.log(scope.user) //undefined
  ...
  });

为什么在我现场直播但未在我的测试中执行此操作?

1 个答案:

答案 0 :(得分:5)

通常,手表是在摘要周期触发的,无论是在初始化时还是由于某些事件。从测试开始,您需要在更改应影响范围或受范围影响的内容后手动运行摘要周期:

$scope.$digest();