简体   繁体   中英

promise testing in angular

I want to test the following method in my controller class:

//  getIds() {
//  this.api.getIds()
//    .then((response)=> {
//      this.ids = response.data;
//      this.doSomethingElse();
//    });
//  }

I'm not sure how to handle the promise using jasmine and karma. The project is written in ES6. api.getIds() returns a $http.get().

beforeEach(function() {

    inject(function($controller, $rootScope, _api_) {

      vm = $controller('MainController', {
        api: _api_,
        $scope:$rootScope.$new()
      });

    });
});

beforeEach(function () {
  vm.getIds();
});

it('should set the ids', function () {
  expect(vm.ids).toBeDefined(); //error
});

How do I wait for the promise to complete before running the expect() ?

First of all, you should use the done callback provided by the jasmine; see async support in Jasmine .

Then, you should mock your getIds on the api so that it returns a resolved promise with an expected value. The asserts should be done after the then promise is called - se bellow the full example.

  beforeEach(function () {
    var $q, vm, api, $controller, $rootScope;

    inject(function (_$controller_, _$rootScope_, _$q_) {
      $q = _$q_;
      $controller = _$controller_;
      $rootScope = _$rootScope_;

      api = jasmine.createSpyObj('api', ['getIds']);
      api.getIds.and.returnValue($q.when([]));

      vm = $controller('MainController', {
        api: api,
        $scope: $rootScope.$new()
      });
    });
  });

  it('should set the ids', function (done) {
    vm
      .getIds()
      .then(function (ids) {
        expect(ids).toBeDefined();
        // add more asserts
        done();
      });
  });

As a side note, if the this.doSomethingElse(); is a promise too, you have to return it in the first then so that you can test the final result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM