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