【发布时间】:2019-03-15 15:22:26
【问题描述】:
我很难在组件初始化后测试某些函数是否绑定到组件。
这是我的 ngOnInit() 函数:
ngOnInit() {
this.someFunction = this.someFunction.bind(this);
}
这是我要绑定到组件的函数::
someFunction() {
// this empty function is not called yet but should be bound to the component
}
这是我之前的:
beforeEach(async(() => {
fixture = TestBed.createComponent(ComponentName);
component = fixture.componentInstance;
fixture.detectChanges();
}));
这是我的描述功能:
describe('ngOnInit', () => {
it('someFunction has been bound to the component.', () => {
let bindFunctionSpy = spyOn(component.someFunction, 'bind').and.callThrough();
component.ngOnInit();
expect(bindFunctionSpy).toHaveBeenCalledWith(component);
});
});
我在这里面临的问题是 spyOn 函数中有一个打字稿错误,阻止我编译测试用例,它说:
错误 TS2345:“绑定”类型的参数不可分配给“从不”类型的参数。
那么我到底在做什么呢?
如果我尝试监视组件函数(例如 apply 或 call)的任何原型函数,也会发生同样的事情。
但是,如果我尝试监视组件变量(如 length 或 toLowerCase)的原型函数,它不会引发此类错误!
另一个注意事项是,这个测试实际上有时会成功编译并实际通过,有时它会在编译时抛出错误,但只有当我进行任何随机更改(例如添加空格然后保存它们以便 Karma 可以检测到)时才会发生这种情况发生了变化并重新编译测试,但如果我关闭终端然后再次启动它并运行 ng test 我再次收到错误。
【问题讨论】:
标签: javascript angular typescript unit-testing jasmine