角度测试函数.bind()

问题描述 投票:0回答:4

在组件初始化后,我很难尝试测试某些功能是否绑定到组件。

这是我的 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
4个回答
2
投票

最好的方法就是将你的函数转换为

CallableFunction
类型。

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


1
投票

你可以试试

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

0
投票

另一种解决方案是使用

Jest
或其他测试框架模拟绑定结果,并通过
expect
方法测试行为。

在这种情况下,我会将函数绑定到组件变量:

{
// my component .ts file.
someFunctionCallback?: Function;

ngOnInit() {
   this.someFunctionCallback = this.someFunction.bind(this);
}
}

通过 jest 框架模拟绑定函数结果进行测试:

// GIVEN
const someFunctionCallbackMock = jest.fn();
spyOn(comp.someFunction, 'bind').and.returnValue(someFunctionCallbackMock);
// if someFunction is private
// spyOn<any>(comp['someFunction'], 'bind).and.returnValue(someFunctionCallbackMock);

// WHEN
component.ngOnInit();

// THEN
expect(comp.someFunctionCallback).toEqual(someFunctionCallbackMock);
// you can test callback as argument
expect(comp.otherSpyiedFunction).toHaveBeenCalledWith(someFunctionCallbackMock)

-1
投票

像这样尝试监视 Function.prototype -

spyOn(Function.prototype, 'bind');

对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.