我有一个组件,它可以像下面这样查询它的内容子级
@ContentChild(InputControlDirective, { read: ElementRef })
public inputControl: ElementRef;
我有ngAfterContentInit钩子,它检查inputControl
是否有值,否则抛出一个自定义错误
public ngAfterContentInit(): void {
if (!this.inputControl) {
throw new Error(
'Provide a InputControlDirective for the field used with the form-input component like <input inputControl>'
);
}
}
如何在下面的单元测试的ngAfterContentInit钩子之前模拟inputControl
?
describe('FormInputComponent', () => {
let component: FormInputComponent;
let fixture: ComponentFixture<FormInputComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [FormInputComponent],
}).compileComponents();
fixture = TestBed.createComponent(FormInputComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
组件实现是不是使单元测试成为一个挑战?
1条答案
按热度按时间ktecyv1j1#
经过一些阅读,我能够弄清楚为什么我嘲笑班级成员的尝试没有奏效。
之前
之后
注意
setTimeout
。关于Angular documentation
延迟的变化检测是有意的和有用的。在Angular启动数据绑定和调用生命周期钩子之前,它为测试人员提供了检查和更改组件状态的机会。