角度测试function.bind()

时间:2019-03-15 15:22:26

标签: javascript angular typescript unit-testing jasmine

在组件初始化之后,我很难测试一下某个组件是否绑定了某些功能。

这是我的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:无法将类型为“ bind”的参数分配给类型为“从不”的参数。

那我到底在做什么呢?

如果我尝试监视诸如apply或call之类的组件函数的任何原型函数,也会发生同样的事情。

但是,如果我尝试监视诸如length或toLowerCase之类的组件变量的原型函数,则不会引发此类错误!

另一个注意事项是,此测试实际上有时会成功编译并通过,有时会在编译时引发错误,但是只有当我进行任何随机更改(例如添加空格然后保存它们,以便Karma可以检测到该错误)时,它才会发生发生了更改并重新编译了测试,但是如果我关闭了终端,然后再次启动它并运行了测试,则会再次收到错误。

3 个答案:

答案 0 :(得分:0)

尝试像这样监视Function.prototype-

spyOn(Function.prototype, 'bind');

对我有用。

答案 1 :(得分:0)

您可以尝试

let bindFunctionSpy = spyOn(component.someFunction.prototype, 'bind').and.callThrough();

答案 2 :(得分:0)

执行此操作的最佳方法就是将函数转换为CallableFunction类型。

let bindFunctionSpy = spyOn(component.someFunction as CallableFunction, 'bind').and.callThrough();