如何测试使用promise的AngularJS组件?

时间:2017-03-30 16:06:21

标签: angularjs unit-testing jasmine

我有以下要进行单元测试的组件。

myApp.component('myComponent', {
  controller: function($q) {
    let serviceDummy = $q((resolve, reject) => resolve(42));
    this.number = 0;
    this.$onInit = () => {
      serviceDummy.then((res) => {this.number = res; });
      serviceDummy.then(console.log);
    }
  },
  template: '<p>The answer is {{$ctrl.number}}</p>'
});

这是我的测试:

describe('myComponent', function() {
  var controller;
  beforeEach(function() {
    module('myApp');
  });
  beforeEach(inject(function($componentController) {
    controller = $componentController('myComponent', null);
  }));

  it('should set the number', function() {
    controller.$onInit();
    expect(controller.number).toBe(42);
  });
});

该组件运行良好但测试失败。 Here is a fiddle

1 个答案:

答案 0 :(得分:0)

首先返回由被测试函数创建的承诺。

this.$onInit = () => {
    //vvvv RETURN promise
    return serviceDummy.then((res) => {this.number = res; });
}

然后使用Jasmine提供的done函数作为it方法的测试处理程序的参数:

  it('should set the number to 42', function testHandler(done) {
    var p = controller.$onInit();
    p.then(function() {
      expect(controller.number).toBe(42);
      done();
    });
    _rootScope.$apply();
  });

DEMO on JSFiddle