gpt4 book ai didi

javascript - Angular Testing function.bind()

转载 作者:行者123 更新时间:2023-12-03 07:13:37 24 4
gpt4 key购买 nike

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

这是我的 ngOnInit() 函数:

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

这是我要绑定(bind)到组件的函数::
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 函数中有一个 typescript 错误,阻止我编译测试用例,它说:

error TS2345: Argument of type '"bind"' is not assignable to parameter of type 'never'.



那么我到底在做什么呢?

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

但是,如果我试图监视组件变量(如长度或 toLowerCase)的原型(prototype)函数,它不会抛出这样的错误!

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

最佳答案

你可以试试

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

关于javascript - Angular Testing function.bind(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55185793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com