【问题标题】:Controller not invoking then with mock service's deferred控制器没有调用模拟服务的延迟
【发布时间】:2026-01-07 21:50:01
【问题描述】:

我试图在服务中模拟一个返回承诺的方法。控制器:

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 再现了该场景。任何帮助将不胜感激。

【问题讨论】:

    标签: angularjs karma-jasmine angular-mock


    【解决方案1】:

    您必须在测试和调用中获得对 $rootScope 的引用:

    $rootScope.$digest()
    

    你的笨拙,重温:

    $digest called and test passed.

    我补充说,您的模拟在解析中没有返回任何内容:

    defer.resolve('Foo');

    HTH

    【讨论】: