【问题标题】:Angular testing function.bind()角度测试 function.bind()
【发布时间】: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


    【解决方案1】:

    你可以试试

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

    【讨论】:

      【解决方案2】:

      最好的方法就是将你的函数转换为 CallableFunction 类型。

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

      【讨论】:

        【解决方案3】:

        尝试像这样监视 Function.prototype -

        spyOn(Function.prototype, 'bind');
        

        它对我有用。

        【讨论】:

        • 如果你使用 Angular Testbed 监视 Function.protype.bind 会引导你到 RangeError: Maximum call stack size exceeded 因为 bind 被调用了很多。
        猜你喜欢
        • 2019-02-15
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        • 2018-11-12
        • 2018-11-19
        • 2018-10-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多