控制器没有调用然后使用模拟服务推迟

时间:2016-05-02 22:20:58

标签: angularjs karma-jasmine angular-mock

我正在尝试在返回promise的服务中模拟一个方法。控制器:

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

1 个答案:

答案 0 :(得分:1)

您必须在测试中获得对$ rootScope的引用并致电:

$rootScope.$digest()

你的插件,重访:

$digest called and test passed.

此外,你的模拟没有回复任何东西,我补充说:

defer.resolve( '富');

HTH