在下面的代码中,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
});
由于该调用在本质上是异步的,您可以在执行任何断言之前注入$ rootScope并调用$ apply函数吗? – Chandermani
我已经注入了$ rootScope,并在我的代码'scope = $ rootScope()。$ new();'中,所以我想我应该添加这一行'scope。$ apply();'在断言之前? – Sunil
是的,这解决了我的问题。你可以请你的建议作为答案吗?所以我只是在说'expect($ state.go.callCount)...'的代码行之前加了scope。$ apply()。 – Sunil