【问题标题】:Unit test angular 1 directive with $on使用 $on 进行单元测试 angular 1 指令
【发布时间】:2017-08-09 02:09:24
【问题描述】:

在这个指令中,我想测试以下内容:

$scope.$on('loggedMsg', function(){
   if($scope.users.length){
       $scope.callingFn();
   }
});

我能够发出loggedMsg$scope.apply(),它将调用$scope.callingFn()。有没有办法不实际调用 $scope.callingFn,而只是监视它?我正在使用 mocha 和 sinon 来编写这些单元测试。我的建议可行吗?

describe('testing directive', function(){
   const elemScope = element.isolateScope;
   it('should trigger callingFn if loggedMsg is emitted', function(){
       scope.$emit('loggedMsg');
       scope.$apply();
       //elemScope.callingFn will be called due to the apply. Is there a way to just spy on that fn being called?
   }
});

【问题讨论】:

    标签: angularjs unit-testing mocha.js sinon


    【解决方案1】:

    当您使用Sinon 存根函数时,调用该(现在已存根)函数将不会调用原始函数。

    Stubs 还支持完整的Spy API,这意味着我们可以使用Stub 来确保原始方法不会被调用,并且还可以查看它在什么条件下被调用(例如多少次,用什么参数)。

    使用您的示例测试:

    describe('testing directive', function(){
       const scope = element.isolateScope;
       it('should trigger callingFn if loggedMsg is emitted', function(){
           const stub = sinon.stub(scope, 'callingFn');
           scope.$emit('loggedMsg');
           scope.$apply();
           assert(stub.called);
       });
    });
    

    文档参考:http://sinonjs.org/releases/v4.1.2/stubs/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 2013-10-18
      • 2017-08-23
      • 1970-01-01
      • 2016-07-25
      相关资源
      最近更新 更多