测试异步组件方法

时间:2017-01-17 11:39:24

标签: angularjs jasmine

我有一个角度组件,我想在调用异步方法后测试状态。我怎样才能做到这一点?我的方法doSomething不会返回一个承诺!

angular.module('myModule').component('myComponent', {
  template: '<p></p>',
  controller: function($q) {
    this.state = 1;
    this.doSomething: function() {
      var that = this;
      setTimeout(function() { that.state = 2; }, 50);
    }
  }
});

测试

describe('Test', function() {
    var ctrl = null;

    beforeEach(module('myModule'));
    beforeEach(inject(function(_$componentController_) {
       ctrl = _$componentController_('myComponent', null, {});
    }));

    it('should be 2', function() {
      ctrl.doSomething();
      expect(ctrl.state).toBe(2);
    });
});

1 个答案:

答案 0 :(得分:0)

您需要等待测试中的更新,如下所示:

describe('Test', function() {
    var ctrl = null;

    beforeEach(module('myModule'));
    beforeEach(inject(function(_$componentController_) {
       ctrl = _$componentController_('myComponent', null, {});
    }));

    it('should be 2', function(done) {
      ctrl.doSomething();
      setTimeout(function() { 
         expect(ctrl.state).toBe(2);
         done(); 
      }, 52);
    });
});
希望这有帮助。