控制器不使用模拟服务的延迟调用
Controller not invoking then with mock service's deferred
我正在尝试在 returns 承诺的服务中模拟一个方法。控制器:
app.controller('MainCtrl', function($scope, foo) {
var self = this;
this.bar = "";
this.foobar = function() {
console.log('Calling the service.');
foo.fn().then(function(data) {
console.log('Received data.');
self.bar = data;
});
}
this.foobar();
});
规范文件:
angular.module('mock.foo', []).service('foo', function($q) {
var self = this;
this.fn = function() {
console.log('Fake service.')
var defer = $q.defer();
defer.resolve('Foo');
return defer.promise;
};
});
describe('controller: MainCtrl', function() {
var ctrl, foo, $scope;
beforeEach(module('app'));
// inject the mock service
beforeEach(module('mock.foo'));
beforeEach(inject(function($rootScope, $controller, _foo_) {
foo = _foo_;
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {$scope: $scope , foo: foo });
}));
it('Should call foo fn', function() {
expect($scope.bar).toBe('Foo');
});
});
调试时,我可以在控制器中看到 promise 对象状态为 1(已解决)。然而,then
中的成功回调从未被调用。
以下 Plunker http://plnkr.co/edit/xpiPKPdjhiaI8KEU1T5V 重现了该场景。任何帮助将不胜感激。
您必须在测试中获取对 $rootScope 的引用并调用:
$rootScope.$digest()
重访你的废话:
$digest called and test passed.
此外,您的模拟没有 return 解析中的任何内容,我补充说:
defer.resolve('Foo');
HTH
我正在尝试在 returns 承诺的服务中模拟一个方法。控制器:
app.controller('MainCtrl', function($scope, foo) {
var self = this;
this.bar = "";
this.foobar = function() {
console.log('Calling the service.');
foo.fn().then(function(data) {
console.log('Received data.');
self.bar = data;
});
}
this.foobar();
});
规范文件:
angular.module('mock.foo', []).service('foo', function($q) {
var self = this;
this.fn = function() {
console.log('Fake service.')
var defer = $q.defer();
defer.resolve('Foo');
return defer.promise;
};
});
describe('controller: MainCtrl', function() {
var ctrl, foo, $scope;
beforeEach(module('app'));
// inject the mock service
beforeEach(module('mock.foo'));
beforeEach(inject(function($rootScope, $controller, _foo_) {
foo = _foo_;
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {$scope: $scope , foo: foo });
}));
it('Should call foo fn', function() {
expect($scope.bar).toBe('Foo');
});
});
调试时,我可以在控制器中看到 promise 对象状态为 1(已解决)。然而,then
中的成功回调从未被调用。
以下 Plunker http://plnkr.co/edit/xpiPKPdjhiaI8KEU1T5V 重现了该场景。任何帮助将不胜感激。
您必须在测试中获取对 $rootScope 的引用并调用:
$rootScope.$digest()
重访你的废话:
$digest called and test passed.
此外,您的模拟没有 return 解析中的任何内容,我补充说:
defer.resolve('Foo');
HTH