以下Angular控制器可以正常工作:
angular.module("mymodule", [])
.service('svc', function($q) {
this.call = function() {
return $q.when(3);
};
})
.controller('MainCtrl', function($scope,svc) {
svc.call()
.then(function successCallback(response) {
$scope.var1 = response;
console.log($scope.var1);
});
});
然而,相关的Jasmin单元测试会返回错误:
describe('Testing a Controller that uses a Promise', function () {
var $scope;
var $q;
var deferred;
beforeEach(module('mymodule'));
beforeEach(inject(function($controller, _$rootScope_, _$q_, svc) {
$q = _$q_;
$scope = _$rootScope_.$new();
deferred = _$q_.defer();
spyOn(svc, 'call').and.returnValue(deferred.promise);
$controller('MainCtrl', {
$scope: $scope,
svc: svc
});
}));
it('should resolve promise', function () {
deferred.resolve(11);
$scope.$apply();
expect($scope.var1).toBe(11);
});
错误:
TypeError:undefined不是构造函数(评估' svc.call() .then(function successCallback(response){ $ scope.var1 =响应; 的console.log($ scope.var1); })')在test / cookbook2.js(第11行)
任何想法如何解决这个问题?