在下面的代码中,userService.addPreference被模拟,$ state.go也是如此,但$ state.go的调用计数始终为零。我在设置userService.addPreference模拟方法时可能会遗漏一些东西吗?
正在进行单元测试的代码
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
});
答案 0 :(得分:1)
服务电话
userService.addPreference(preference).then(function (dashboard) {
$state.go('authenticated.dashboard.grid', {id: dashboard.id});
});
涉及异步回调,除非我们明确告诉它,否则不会触发。要强制回调评估,我们需要使用$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
});
请记住,顺序流回调永远不会被触发。