如何在角度js中添加观察者?

时间:2016-01-02 12:05:36

标签: angularjs angularjs-directive angularjs-scope jasmine karma-jasmine

我正在尝试在我的演示中添加观察者。我可以在这样的对象中添加监视

$scope.$watch('username',function(newvalue,oldvalue){
        console.log(newvalue +":"+oldvalue);
        $scope.newmessage=newvalue.toUpperCase();
    })

它运行正常。但是当我尝试测试它时,我的错误就是我的代码

describe('value check', function() {
  var $scope,
    ctrl,
    fac,
    $httpBackend;
  beforeEach(function() {
    module('app');

  });
  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  beforeEach(inject(function($rootScope, $controller, _$httpBackend_) {
    $scope = $rootScope.$new();
    $httpBackend = _$httpBackend_;

    createController = function() {
      return $controller('cntrl', {
        '$scope': $scope
      });
    };

  }));

  describe('watch check', function() {
    beforeEach(function() {
      $scope.$digest();
    });

    it('should init', function(){
      expect($scope.newmessage).toBeUndefined();
    });

    it('should upper case',function() {
      var controller = createController();
      $scope.message='naveen';
      $scope.$digest();
      expect($scope.newmessage).toEqual('NAVEEN');
    });
  });


  it("tracks that the spy was called", function() {
    var response = [{
      "name": "naveen"
    }, {
      "name": "parveen"
    }]
    $httpBackend.whenGET('data.json').respond(response);
    var controller = createController();

    $httpBackend.expectGET('data.json').respond(response);

    $scope.getData();
    $httpBackend.flush();

    expect($scope.data[0].name).toEqual('naveen')
  });
});

Plunker

http://plnkr.co/edit/NhazRDVM01DCDQWw8yzV?p=preview

1 个答案:

答案 0 :(得分:1)

第一个错误是意外请求,可以通过在should uppercase测试用例中模拟data.json请求来解决。

可以通过$scope.username = 'naveen'代替$scope.message = 'naveen'来修复第二个错误,因为您实际上正在关注用户名更改,而不是消息更改。

第三个错误是,当您初始化监视时,它会被未定义的新值触发。要解决此问题,请检查控制器中是否未定义:

if (newvalue) {
       $scope.newmessage = newvalue.toUpperCase();
}

请参阅plunker:http://plnkr.co/edit/OBUcoNGPdfRwy3hwR4KZ?p=preview