[英]Angular 6 unit testing detectChange throws error for component with @input
I have a simple component that is passed a config object as @input
and uses it to set some values in ngOnInit
我有一个简单的组件,该组件将一个配置对象作为@input
传递给它,并使用它在ngOnInit
设置一些值
export class MyComponent implements OnInit {
@input() config: ConfigObject;
min: number;
max: number;
ngOnInit() {
this.min = this.config.range.min;
this.max = this.config.range.max;
}
}
And I test it as follows: 我对其进行如下测试:
describe('MyComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({...})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.config = <ConfigObject>mockConfig;
fixture.detectChanges();
})
})
detectChanges
here will throw an error [object ErrorEvent] thrown
. detectChanges
会抛出一个错误[object ErrorEvent] thrown
。 If I call ngOnInit
explicitly, I will receive TypeError: Cannot read property 'min' of undefined
. 如果我显式调用ngOnInit
,我将收到TypeError: Cannot read property 'min' of undefined
。 From Angular's testing guide it seems like it should be possibly to set input explicitly on tested component, and then call detectChanges
so I'm not sure why this isn't working. 从Angular的测试指南看来,似乎应该在经过测试的组件上显式设置输入,然后调用detectChanges
所以我不确定为什么这不起作用。
In case you were wondering - the mockConfig
object is a copy of the object passed to the component when code is run, and the component does not error in this case. 万一您想知道, mockConfig
对象是运行代码时传递给组件的对象的副本,在这种情况下组件不会出错。
You need to give some mock value please check it now, it should work 您需要提供一些模拟值,请立即检查它,它应该可以工作
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.config = range: {min:0, max:100};
fixture.detectChanges();
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.