Vit*_*gon 5 unit-testing angular
如何从单元测试中访问注入的ngControl?如何解决错误?
在组件中
constructor(
@Self() @Optional() public ngControl: NgControl
) { }
ngOnInit(): void {
this.ngControl.valueChanges
Run Code Online (Sandbox Code Playgroud)
在单元测试中
beforeEach(() => {
fixture = TestBed.createComponent(component);
fixture.detectChanges();
Run Code Online (Sandbox Code Playgroud)
执行测试时得到错误
TypeError: Cannot read property 'valueChanges' of null
小智 12
我通过重写解决了这个问题
beforeEach(async () => {
const NG_CONTROL_PROVIDER = {
provide: NgControl,
useClass: class extends NgControl {
control = new FormControl();
viewToModelUpdate() {}
},
};
await TestBed.configureTestingModule({
declarations: [YourComponentName],
imports: [FormsModule],
})
.overrideComponent(YourComponentName, {
add: { providers: [NG_CONTROL_PROVIDER] },
})
.compileComponents();
});
Run Code Online (Sandbox Code Playgroud)
适用于:
beforeEach(() => {
fixture = TestBed.createComponent(?omponent);
(fixture.componentInstance as any).ngControl = new FormControl();
Run Code Online (Sandbox Code Playgroud)