繁体   English   中英

承诺在角度测试

[英]promise testing in angular

我想在控制器类中测试以下方法:

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

我不确定如何使用茉莉花和业力来兑现诺言。 该项目是用ES6编写的。 api.getIds()返回$ 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
});

如何在运行Expect()之前等待诺言完成?

首先,您应该使用茉莉花提供的done回调; 请参阅Jasmine中的异步支持

然后,您应该在api上模拟您的getIds ,以便它返回具有期望值的已解决的Promise。 断言应该在then promise调用之后完成-在下面的完整示例中。

  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();
      });
  });

附带说明一下,如果this.doSomethingElse(); 也是一个承诺,您必须先返回它, then才能测试最终结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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