如何对依赖于承诺的AngularJS控制器进行单元测试?

Sha*_*oon 2 javascript unit-testing promise angularjs

在我的控制器中,我有:

  $scope.index = function() {
    CompanyService.initialized.then(function() {
      var company_id = CompanyService.getCompany()._id;
      LocationService.list(company_id, $routeParams.location_parent_id).then(function(response) {
        if(response.data.status === 'ok') {
          $scope.locations = response.data.locations;
          $scope.current_location = response.data.location || null;
        }
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

所以它应该得到LocationService列表,测试如下:

it('should get locations', function() {
  $httpBackend.when('GET', '/api/v1/location/list').respond({status: 'ok', locations: ['loc1', 'loc2']})
  $scope.index();
  expect($scope.locations.length).toEqual(2);
Run Code Online (Sandbox Code Playgroud)

但是,这种情况从未发生过,因为它CompanyService具有永远不会在单元测试中得到解决的承诺.我如何嘲笑退回的承诺CompanyService或绕过它?

Mik*_*378 5

只需使用createSpyObjJasmine中的方法模拟调用 :

describe('one test', function(){

 var deferred, CompanyService, $scope;

 beforeEach(inject(function ($q, $rootScope, $controller) {
  params = {
        $scope: $rootScope.$new(),
        CompanyService = jasmine.createSpyObj('CompanyService', ['initialized'])
  }
  params.CompanyService.initialized.andCallFake(function () {
      deferred = $q.defer();
      return deferred.promise;  //will fake to return a promise, in order to reach it inside the test
    });
  $controller('YourController', params);
 });

 it('my test', function(){
     deferred.resolve({}); //empty object returned for the sample but you can set what you need to be returned
     $scope.$digest(); //important in order to resolve the promise
    //at this time, the promise is resolved! so your logic to test can be placed here
 });
});
Run Code Online (Sandbox Code Playgroud)