带有$ on的单元测试角度1指令

时间:2017-08-09 02:09:24

标签: angularjs unit-testing mocha sinon

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

{
    totalSales: "960.00",
    year: 2017
},
{
    totalCost: "792.00",
    year: 2017
}

我能够发出$scope.$on('loggedMsg', function(){ if($scope.users.length){ $scope.callingFn(); } }); loggedMsg,它会调用$ scope.callingFn()。有没有办法不实际调用$ scope.callingFn,但只是窥探它?我正在使用mocha和sinon来编写这些单元测试。我建议可能吗?

$scope.apply()

1 个答案:

答案 0 :(得分:0)

当您使用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/