我的服务如下:
app.service('foo',function($q){
this.fn3 = function(){
var deferred = $q.defer();
return deferred.promise;
}
});
我的规范文件如下:
describe('Testing: MainCtrl', function() {
var $scope = null;
var ctrl = null;
var mockfoo;
var deferred;
var $q;
var data = {name: 'test'};
var createController;
beforeEach(module('plunker'));
beforeEach(inject(function($rootScope, $controller,_$q_) {
$scope = $rootScope.$new();
$q = _$q_;
mockfoo = {
fn3: function(){ }
};
deferred = $q.defer();
spyOn(mockfoo,'fn3').and.returnValue(deferred.promise);
createController = function() {
return $controller('MainCtrl', {
$scope: $scope,
foo: mockfoo
});
};
}));
it('Should call fn3()', function(){
ctrl = createController();
deferred.resolve(data);
$scope.$digest();
expect(mockfoo.fn3).toHaveBeenCalled();
expect($scope.temp).toBe(data);
});
});
我不清楚为什么这个规格失败了。我正在解析承诺,然后调用$ digest,这意味着$ scope.temp应该得到一个值。
我在这里有一个plnkr: http://plnkr.co/edit/uzWqTT
有人建议吗?
答案 0 :(得分:0)
通过访问then
函数中的值
var resolvedValue;
$scope.temp.then(function(value) { resolvedValue = value; });
expect(resolvedValue).toEqual(data);
请参阅plunker。