在 Jasmine 和 AngularJS 的承诺的一部分中对方法的调用计数进行单元测试
Unit test the call count of method in then part of a promise in Jasmine and AngularJS
在下面的代码中,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
});
服务调用
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
});
请记住,顺序流回调永远不会触发。
在下面的代码中,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
});
服务调用
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
});
请记住,顺序流回调永远不会触发。