假设我有一个组件InputComponent
,它实现了ControlValueAccessor
。现在,我有AnotherComponent
,它像这样使用第一个组件:
<my-input [(ngModel)]="text"></my-input>
我正在尝试测试AnotherComponent
,并且设置了NO_ERRORS_SCHEMA
选项。在测试中,我需要在ngModel
中添加一些值以模拟用户输入。
这是我尝试过的:
const input = fixture.debugElement.query(By.css('my-input'));
input.nativeElement.value = 'some string';
input.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
await fixture.whenStable();
// then I assert that AnotherComponent `text` property is equal to the one I set to `ngModel`
但是text
属性为空,我在做什么错?
P.S。根据要求添加了TestBed
,但是该测试相当普遍。
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AnotherComponent ],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AnotherComponent);
fixture.detectChanges();
});
为了使ngModel
工作,您还需要在测试中导入FormsModule
:
TestBed.configureTestingModule({
imports: [ FormsModule ],
declarations: [ AnotherComponent ],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();