我想测试实现ControlValueAccessor接口的组件,以允许在我的自定义组件中使用[(ngModel)]
,但问题是通常的输入是正确的,但ngModel
- undefined
。这是代码示例:
@Component({
template: `
<custom-component
[usualInput]="usualInput"
[(ngModel)]="modelValue"
></custom-component>`
})
class TestHostComponent {
usualInput: number = 1;
modelValue: number = 2;
}
describe('Component test', () => {
let component: TestHostComponent;
let fixture: ComponentFixture<TestHostComponent>;
let de: DebugElement;
let customComponent: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
CustomComponent,
],
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
}));
});
所以,我希望我的customComponent中的regularInput Input()值等于1(它是真的),并且ngModel值将等于2,但是ngModel = undefined并且在调试之后我知道ControlValueAccessor writeValue方法不会在测试中调用环境(但它适用于浏览器)。那么我该如何解决呢?
答案 0 :(得分:0)
在join
组件内部,您无权访问ControlValueAccessor
,除非您注入了该组件并且做了一些技巧来避免循环依赖。
ngModel
具有ControlValueAccessor
方法,该方法在更新时从控件接收值-如果需要,可以将该值存储在组件中,然后对其进行测试。
答案 1 :(得分:0)
您必须使用异步包装测试,然后等待fixture.whenStable
it('should get ngModel', async(() => { let customComponent = debugEl.query(By.directive(CustomComponent)); fixture.whenStable().then(() => { fixture.detectChanges(); expect(customComponent.componentInstance.value).toEqual(2); }); });