简体   繁体   English

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

[英]Why do I exactly need detectChanges in angular2?

I have the following code: 我有以下代码:

  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"); 
});

Regardless of fixture.detectChanges() the element1.textContent() changes to the value of "new"? 不管fixture.detectChanges()为何,element1.textContent()都更改为“ new”的值? Shouldn't the change happen only if I call the detectChanges() function?. 仅当我调用detectChanges()函数时,更改才会发生吗? Otherwise, what is the point of having detectChanges anyway since the change is registered without the function being called? 否则,由于在未调用函数的情况下注册了更改,因此无论如何都具有detectChanges有什么意义?

Basically I expect my last expect function to pass the test since the changes shouldn't have had been registered with the element1.textContent="new" because of not calling the detectChanges function 基本上,我希望我的最后一个Expect函数能够通过测试,因为不应该因为未调用detectChanges函数而将更改注册到element1.textContent =“ new”

You're not testing your component correctly. 您没有正确测试组件。 You're not suppose to change the fixture's contents. 您不打算更改灯具的内容。 You want to change the components properties and check if the fixture has changed accordingly, and for this you will need the detectChanges() method. 您想要更改组件属性,并检查灯具是否进行了相应更改,为此,您将需要detectChanges()方法。

Example: 例:

app.component.ts app.component.ts

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

app.component.spec.ts 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');
});

To answer your question directly you need the fixtures detectChanges() method in order to detect changes that happened inside the component and re-render the fixture. 要直接回答您的问题,您需要使用夹具的detectChanges()方法来检测组件内部发生的更改并重新渲染夹具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM