[英]Angular 2(4) component with ControlValueAccessor testing
I would like to test component which implements ControlValueAccessor interface for allow to use [(ngModel)]
in my custom component, but the issue is that usual inputs comes correct but ngModel
- undefined
.我想测试实现 ControlValueAccessor 接口的组件,以允许在我的自定义组件中使用
[(ngModel)]
,但问题是通常的输入正确但ngModel
- undefined
。 Here is code example:这是代码示例:
@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();
}));
});
So, I expect usualInput Input() value in my customComponent will equal 1 (it is true), and ngModel value will equal 2, but ngModel = undefined and after debug I know that ControlValueAccessor writeValue method doesn't call in test environment (but it works correct for browser).所以,我希望 customComponent 中的 commonInput Input() 值等于 1(这是真的),ngModel 值等于 2,但是 ngModel = undefined 并且在调试之后我知道 ControlValueAccessor writeValue 方法不会在测试环境中调用(但是它适用于浏览器)。 So how can I fix it?
那么我该如何解决呢?
Inside your ControlValueAccessor
component you do not have access to ngModel
unless you injected it and did some tricks to avoid circular dependency.在您的
ControlValueAccessor
组件中,您无权访问ngModel
除非您注入它并做了一些技巧来避免循环依赖。
ControlValueAccessor
has writeValue
method which receives values from control when it is updated — if you need, you can store this value in your component and then test it. ControlValueAccessor
具有writeValue
方法,该方法在更新时从控件接收值——如果需要,您可以将此值存储在您的组件中,然后对其进行测试。
You have to wrap your test with async, and wait for fixture.whenStable
你必须用异步包装你的测试,并等待
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); }); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.