在进行Angular 2+单元测试时,调用fixture.detectChanges()
会触发组件的变化检测,但有时候会发现组件的属性被移除了。这通常是因为在测试过程中,组件的属性被修改或重新赋值,而fixture.detectChanges()
会重新渲染组件并应用最新的属性。
为了解决这个问题,可以采用以下两种方法之一:
fixture.detectChanges()
之前,先保存组件的属性值,在detectChanges()
之后再重新赋值。这样可以确保在重新渲染组件之后,属性值仍然存在。it('should update component property', () => {
component.property = 'new value';
const originalValue = component.property;
fixture.detectChanges();
expect(component.property).toBe(originalValue);
});
ComponentFixture.autoDetectChanges()
方法,该方法会在每次对组件进行更改时自动调用detectChanges()
。这样可以确保在每次更改后都会进行变化检测,而不需要手动调用detectChanges()
。beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.autoDetectChanges(true);
});
通过使用以上方法,可以确保在进行单元测试时,组件的属性不会被意外移除。