Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何测试使用promise的AngularJS组件?_Angularjs_Unit Testing_Jasmine - Fatal编程技术网

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

如何测试使用promise的AngularJS组件?,angularjs,unit-testing,jasmine,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; });

我想对以下组件进行单元测试

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>'
});
该组件工作正常,但测试失败。 首先返回被测函数创建的承诺

this.$onInit = () => {
    //vvvv RETURN promise
    return serviceDummy.then((res) => {this.number = res; });
}
然后使用Jasmine提供的Then
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();
  });
在expect之前添加$rootScope.$digest()
  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();
  });