【问题标题】:Angular 2 testing, template update not being detectedAngular 2 测试,未检测到模板更新
【发布时间】:2017-08-26 06:08:14
【问题描述】:

我正在测试一个组件,当调用 ngAfterViewInit 生命周期挂钩时,该组件会动态地在其模板中插入一个复选框。

export class MyComponent {

  ngAfterViewInit() {
    // checkbox insertion in the template here
    ...
  }

  ...
}

这是我的测试:

it('should inject the checkbox', () => {
  fixture = TestBed.createComponent(AutogeneratedTableComponent);
  fixture.detectChanges();

  rows = fixture.debugElement.queryAll(By.css('tr'));
  console.log(Object.assign({}, rows[1].nativeElement));  // *referenceLog
  console.log(rows[1].nativeElement));  // *cloneLog

  expect(rows[1].query(By.css('input')).not.toBeNull(); // FAILS
}

*refereceLog(打印没有插入 td 的 tr)

<tr ng-reflect-id="22" id="22">
   <td>Single Room</td>
   <td>My single room.</td>
</tr>

*cloneLog(表示测试时模板还没有准备好)

Object{__zone_symbol__eventTasks: [ZoneTask{zone: ..., runCount: ..., _zoneDelegates: ..., _state: ..., type: ..., source: ..., data: ..., scheduleFn: ..., cancelFn: ..., callback: ..., invoke: ...}]}

我尝试手动调用 ngAfterViewInit()

it('should inject the checkbox', () => {
  fixture = TestBed.createComponent(AutogeneratedTableComponent);
  fixture.detectChanges();

  fixture.debugElement.componentInstance.ngAfterViewInit();
  fixture.detectChanges();

  rows = fixture.debugElement.queryAll(By.css('tr'));
  console.log(Object.assign({}, rows[1].nativeElement));  // *referenceLog
  console.log(rows[1].nativeElement));  // *cloneLog

  expect(rows[1].query(By.css('input')).not.toBeNull(); // FAILS
}

*refereceLog(打印预期的 tr)

<tr ng-reflect-id="22" id="22">
   <td><input id="22" type="checkbox"></td>
   <td>Single Room</td>
   <td>My single room.</td>
</tr>

*cloneLog 没有变化

然后我尝试了

  • 添加spyOn(component, 'ngAfterViewInit').andReturnValue(Promise.resolve(true)).and.callThrough(); 然后spyOn().calls.mostRecent.returnValue.then(() => {fixture.detectChanges() ... }) 与底部的done()

  • async() 添加到单个测试声明并执行 fixture.whenStable.then( () => { fixture.detectChanges()... } )

  • 中的评估
  • fakeAsync() 添加到单个测试声明和tick() 评估前调用

所有尝试都具有相同的先前结果。评估完成后正在更新模板元素。

我应该找到一种方法来停止测试执行,直到我正在测试的 nativeElement 被更新。

【问题讨论】:

    标签: angular angular2-testing


    【解决方案1】:

    我遇到了类似的问题,这个解决方案对我有用:

    我打电话给fixture.autoDetectChanges(true);,而不是(或另外)fixture.detectChanges()

    【讨论】:

    • 太棒了,经过几个小时的搜索,找到了这个答案。您能否指出您在其中找到此建议的任何文档?谢谢
    • 仍然适用于 Angular 9 ?
    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 2012-10-25
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多