使用Jasmine测试嵌套的AngularJS承诺

时间:2016-04-13 13:37:17

标签: javascript angularjs unit-testing jasmine angular-mock

我希望测试嵌套的承诺,我不知道该怎么做。

我将如何测试这样的场景?

angular.module('moduleA')
   .factory('serviceA', function(serviceB){

  return {
      create: create
  }

  function create(){

    return serviceB.create().then(function(d){

        serviceB.doSomething();

        return $state.go("app.list", { id: d.id }).then(function(){

            serviceB.doSomethingElse();

        });

    })

  };
}); 

我想测试的地方

    expect(serviceB, 'create').toHaveBeenCalled();
    expect($state, 'go').toHaveBeenCalledWith("app.list", { id: newId });
    expect(serviceB, 'doSomething').toHaveBeenCalled();
    expect(serviceB, 'doSomethingElse').toHaveBeenCalled();

这是我的尝试:

describe('serviceA spec', function () {

var $rootScope, $state, serviceA, serviceB;

beforeEach(function () {

    $state = {
        go: function(){}
    }

    serviceB = {
        create: {},
        doSomething: {},
        doSomethingElse: {}
    }

    module('app', function($provide){
        $provide.value('serviceB', serviceB);
        $provide.value('$state', $state);
    });

    inject(function (_$rootScope_, _serviceA_) {
        serviceA =_serviceA_;
        $rootScope = _$rootScope_;
    });
});

it('should create', function(){

    var newId = "555";

    spyOn($state, 'go').and.callFake(function () {
        var deferred = $q.defer();
        deferred.resolve({});
        return deferred.promise;
    });

    spyOn(serviceB, 'create').and.callFake(function () {
        var deferred = $q.defer();
        deferred.resolve({ id: newId });
        return deferred.promise;
    });

    spyOn(serviceB, 'doSomething');
    spyOn(serviceB, 'doSomethingElse');

    serviceA.create();

    expect(serviceB, 'create').toHaveBeenCalled();
    expect($state, 'go').toHaveBeenCalledWith("app.list", { id: newId });
    expect(serviceB, 'doSomething').toHaveBeenCalled();
    expect(serviceB, 'doSomethingElse').toHaveBeenCalled();

    $rootScope.$digest();

});

});

非常感谢任何建议

1 个答案:

答案 0 :(得分:0)

在每个承诺之后,您必须致电$rootScope.$apply(),以便兑现承诺。