【问题标题】:Angular 2 unit test must call whenStable multiple times when nesting ngModel elements嵌套ngModel元素时,Angular 2单元测试必须多次调用whenStable
【发布时间】:2016-12-22 00:19:09
【问题描述】:

我很清楚这里有这个错误:

https://github.com/angular/angular/issues/10148

其中提到需要先拨打fixture.detectChanges();,然后拨打fixture.whenStable()

但是,当我开始嵌套元素时,每个元素都使用 ngModel 值访问器提供程序,我必须在循环中调用这两个方法。

有没有其他方法可以做到这一点?它似乎效率不高,我经常需要编辑这个函数。我可以使用递归方法来简化它以防止重复,但这不是问题。

export function bugWhenStable(fixture: ComponentFixture<any>): Promise<any> {
    let def = new Promise(resolver => {
        fixture.detectChanges();
        fixture.whenStable().then(() => {
            fixture.detectChanges();
            fixture.whenStable().then(() => {
                fixture.detectChanges();
                fixture.whenStable().then(() => {
                    resolver();
                });
            });
        });
    });

    return def;
}

我的组件做这样的事情:

<wm-comp1 [(ngModel)]="value"></wm-comp1>

我在 Comp1 中有哪些

<wm-comp2 [(ngModel)]="value"></wm-comp2>

等等

【问题讨论】:

  • 我遇到了同样的问题 - 你有没有找到更好的方法?
  • @wags1999 不,仍然是同样的问题。我注意到多次运行时稳定并没有显着减慢我的测试速度......但是,它非常难看。创建 testBed 和组件是最慢的部分。
  • 感谢发布这个问题,感谢大家的回答,你拯救了我的一天:)

标签: angular testing


【解决方案1】:

为什么不使用async/await

it('should do whatever', async(async() => {
  fixture.detectChanges();
  await fixture.whenStable();
}));

【讨论】:

  • 问题是你必须多次调用它。你做得很漂亮,但你仍然需要循环它。我在上面的错误中提到了这一点。
  • 是的,您可以在 util 函数中对其进行变形,以循环多次
  • 我明白这一点,但我的主要问题是如何避免这种情况。如何避免像嵌套 ngModels 一样多次调用 detectChanges。
【解决方案2】:

您是否尝试过将承诺返回到下一个然后 fn?这将使它等待直到它得到解决。我在我的规格中尝试过一次,效果很好。看起来更干净。

export function bugWhenStable(fixture: ComponentFixture<any>): Promise<any> {
  let def = new Promise(resolver => {
    fixture.detectChanges();
    fixture.whenStable()
      .then(() => {
        fixture.detectChanges();

        return fixture.whenStable();
      }).then(() => {
        fixture.detectChanges();

        return fixture.whenStable()
      }).then(() => {
        resolver();
      });
  });

  return def;
}

也有人喜欢这样做,但我从未尝试过。

export function bugWhenStable(fixture: ComponentFixture<any>): Promise<any> {
  let def = new Promise(resolver => {
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    tick();
    fixture.detectChanges();
    tick();
    resolver();
  });
});

return def;
}

【讨论】:

    猜你喜欢
    • 2017-03-07
    • 1970-01-01
    • 2017-08-28
    • 2016-12-29
    • 1970-01-01
    • 2017-04-04
    • 2018-09-10
    • 2018-04-11
    相关资源
    最近更新 更多