为什么我确实需要angular2中的detectChanges?

时间:2017-09-23 09:34:10

标签: javascript angular karma-jasmine

我有以下代码:

  it ("test detect change", async()=>{
     let fixture= TestBed.createComponent(AppComponent);
     let element1= fixture.debugElement.nativeElement.querySelector("h1");
     expect(element1.textContent).toContain("come"); 
     element1.textContent="new";
     //fixture.detectChanges();
     expect(element1.textContent).toContain("come"); 
});

无论fixture.detectChanges()如何,element1.textContent()都会更改为" new"?的值只有在我调用detectChanges()函数时才会发生变化吗?否则,无论如何都要检测更改是什么意思,因为在没有调用函数的情况下注册了更改?

基本上我希望我的最后期望函数能够通过测试,因为更改不应该已经注册到element1.textContent =" new"因为没有调用detectChanges函数

1 个答案:

答案 0 :(得分:1)

您未正确测试组件。您不应该更改灯具的内容。您想要更改组件属性并检查夹具是否相应更改,为此您需要detectChanges()方法。

示例:

  

app.component.ts

@Component({
  selector   : 'app-root',
  template: '<h1>{{ title }}</h1>',
})
export class AppComponent {
  title = 'Test';
}
  

app.component.spec.ts

it('should change the title', () => {
  const compiled = fixture.debugElement.nativeElement;
  const component = fixture.componentInstance;

  expect(compiled.querySelector('h1').textContent).toBe('Test');
  component.title = 'New';
  fixture.detectChanges(); // <- Required for the following expectation to pass
  expect(compiled.querySelector('h1').textContent).toBe('New');
});

要直接回答您的问题,您需要使用灯具detectChanges()方法来检测组件内发生的变化并重新渲染灯具。