2015-05-01 40 views
0

在下面的代码中,userService.addPreference被模拟,$ state.go也是如此,但仍然是$ state.go的调用计数零。有没有我可能错过了userService.addPreference模拟方法的设置?单元测试Jasmine和AngularJS承诺的部分方法的呼叫计数

码正被单元测试

 userService.addPreference(preference).then(function (dashboard) { 
       $state.go('authenticated.dashboard.grid', {id: dashboard.id}); 
      }); 

单位测试嘲笑方法和单元测试

sinon.stub(userService, 'addPreference', function (preference) { 
       var defer = $q.defer(); 
       defer.resolve(preference); 
       return defer.promise; 
      }); 
sinon.stub($state, 'go', function() { }); 
    it('dashboard.confirm should call $state.go', function() { 
     vm.confirm();//this is the function containing code being unit tested 
     expect($state.go.callCount).to.equal(1);//this is always ZERO and so failing 
    }); 
+1

由于该调用在本质上是异步的,您可以在执行任何断言之前注入$ rootScope并调用$ apply函数吗? – Chandermani

+0

我已经注入了$ rootScope,并在我的代码'scope = $ rootScope()。$ new();'中,所以我想我应该添加这一行'scope。$ apply();'在断言之前? – Sunil

+0

是的,这解决了我的问题。你可以请你的建议作为答案吗?所以我只是在说'expect($ state.go.callCount)...'的代码行之前加了scope。$ apply()。 – Sunil

回答

1

服务调用

userService.addPreference(preference).then(function (dashboard) { 
       $state.go('authenticated.dashboard.grid', {id: dashboard.id}); 
      }); 

涉及异步CAL lback,除非我们明确告诉它,否则它不会启动。要强制回调,以评估我们需要运行使用$scope.$apply摘要周期,因此改变你的测试代码:

it('dashboard.confirm should call $state.go', function() { 
     vm.confirm();//this is the function containing code being unit tested 
     $scope.$apply(); 
     expect($state.go.callCount).to.equal(1);//this is always ZERO and so failing 
    }); 

记得是一个连续的流回调从未被触发。

+0

你的意思是测试异步回调通常不会被触发? – Sunil

+1

因为javascript是单线程执行,所以一旦你做了异步调用,没有任何东西等待结果,并且你继续下一步,在你的情况下,它会被断言并失败。通过做$申请你迫使Angular评估回调, – Chandermani

+1

太好了。你在这么短的时间里教过我很多。谢谢。 – Sunil