Javascript 为什么我真的需要angular2中的detectChanges?
我有以下代码:Javascript 为什么我真的需要angular2中的detectChanges?,javascript,angular,karma-jasmine,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.
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.detect如何更改element1.textContent的值为new?只有在调用detectChanges函数时才会发生更改吗?。否则,既然更改是在没有调用函数的情况下注册的,那么使用detectChanges有什么意义呢
基本上,我希望我的上一个expect函数能够通过测试,因为更改不应该在element1中注册。textContent=new,因为没有调用detectChanges函数。您没有正确测试组件。您不应该更改夹具的内容。您需要更改零部件属性并检查夹具是否已相应更改,为此,您需要使用detectChanges方法 例如: app.component.ts app.component.spec.ts
要直接回答您的问题,您需要fixtures detectChanges方法,以便检测组件内部发生的更改并重新呈现fixture。我也这么认为,请使用tnx作为回答。这不是问题。很高兴我能帮助你。
@Component({
selector : 'app-root',
template: '<h1>{{ title }}</h1>',
})
export class AppComponent {
title = 'Test';
}
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');
});