1.在测试文件中引入ChangeDetectorRef:
import { Component, ChangeDetectorRef } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing';
2.对于每个测试用例,在BeforeEach块中创建一个新的实例,并使用changeDectectorRef的detectChanges方法手动调用变更检测:
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture
beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ MyComponent ] }) .compileComponents(); });
beforeEach(() => { fixture = TestBed.createComponent(MyComponent); component = fixture.componentInstance; changeDetectorRef = fixture.debugElement.injector.get(ChangeDetectorRef); fixture.detectChanges(); });
it('should update input value', () => { component.myInputValue = 'new value'; changeDetectorRef.detectChanges(); expect(component.myInputValue).toEqual('new value'); }); });
3.确保对应的组件输入属性有输入绑定:
@Component({
template:
})
export class MyComponent {
@Input() myInputValue: string;
}