在单元测试中,使用fixture.detectChanges()
来触发Angular变更检测,并更新组件属性。
下面是一个示例代码,展示如何在单元测试中更新组件属性:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MyComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should update component property using ngModel', () => {
const inputElement = fixture.nativeElement.querySelector('input');
inputElement.value = 'New Value';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(component.myProperty).toBe('New Value');
});
});
在上面的示例中,我们使用fixture.detectChanges()
来触发Angular变更检测,并更新组件属性。然后,我们获取输入元素,并模拟输入新的值。接着,我们再次调用fixture.detectChanges()
来更新组件,并验证组件属性是否正确更新。