我有以下代码:
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”值?难道只有当我调用 detectorChanges() 函数时才会发生更改吗?否则,既然更改是在没有调用函数的情况下注册的,那么检测更改有什么意义呢?
基本上,我希望我的最后一个期望函数能够通过测试,因为由于没有调用 detectorChanges 函数,所以不应使用 element1.textContent="new"注册更改
最佳答案
您没有正确测试您的组件。您不应该更改灯具的内容。您想要更改组件属性并检查夹具是否已相应更改,为此您需要 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()
方法来检测组件内部发生的更改并重新渲染固定装置。
关于javascript - 为什么我确实需要 angular2 中的 detectorChanges ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46378125/