【问题标题】:toHaveBeenCalledWith() error: Expected 2 arguments, but got 1toHaveBeenCalledWith() 错误:预期 2 个参数,但得到 1 个
【发布时间】:2022-01-18 14:26:53
【问题描述】:

在组件 .ts 文件中

onScrollToProductSelector(){
   let offset = document.getElementById("selector").offsetTop;
   window.scrollBy({
      top: offset,
      behavior: "smooth"
   });
}

.spec.ts 文件中

it("should call window.scrollby", () => {
        spyOn<any>(window, "scrollBy");
        let topOffset = fixture.debugElement.nativeElement.querySelector("#selector").offsetTop;
        const mockObj = {
            top: topOffset,
            behavior: "smooth"
        }
        component.onScrollToProductSelector();
        expect(window.scrollBy).toHaveBeenCalledWith(mockObj);
});

但是当我运行这个测试用例时,我收到以下错误:

错误 TS2554:预期有 2 个参数,但得到了 1 个。

【问题讨论】:

  • 在哪一行显示错误?
  • @AakashGarg 这一行expect(window.scrollBy).toHaveBeenCalledWith(mockObj);
  • 尝试将 expect(window.scrollBy).toHaveBeenCalledWith(mockObj) 更改为 expect(window.scrollBy).toHaveBeenCalledWith(mockObj, undefined)。如果可行,请告诉我,我会将其作为答案。
  • @aakashgarg 没用。现在它给第一个参数另一个错误说: {top: number, behavior:string} 类型的参数不能分配给 number 类型的参数 | asymetricMatcher

标签: angular jasmine karma-jasmine angular11


【解决方案1】:

这个问题是由于DefinitelyTyped问题#42455造成的。

Window.scrollBy() 是一个重载方法。

window.scrollBy(x-coord, y-coord);
window.scrollBy(options) 

您在代码中使用的是 window.scrollBy(options) 版本,但 toHaveBeenCalledWith 尝试查找 window.scrollBy(x-coord, y-coord) 的匹配项。

显然有一些方法可以解决这个问题。仔细阅读DefinitelyTyped 问题#42455 中的 cmets,然后选择最适合您的。

【讨论】:

  • 谢谢,@uminder 这个解决方案已经奏效了。
【解决方案2】:

正如@uminder 建议的#42455

window.scrollBy 是一个重载方法,默认考虑 2 参数重载方法。 window.scrollBy(x, y);

解决方案是: 不检查是否使用 ... 参数调用该方法,检查第一个参数是否为 ... 参数对象。

it("should call window.scrollby", () => {
        let spyCall = spyOn<any>(window, "scrollBy");
        let topOffset = fixture.debugElement.nativeElement.querySelector("#selector").offsetTop;
        const mockObj = {
            top: topOffset,
            behavior: "smooth"
        }
        component.onScrollToProductSelector();
        expect(spyCall.calls.argsFor(0)).toEqual([mockObj]);
});

【讨论】:

    猜你喜欢
    • 2020-05-19
    • 2019-11-04
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 2021-03-13
    • 2018-05-19
    • 2018-09-07
    相关资源
    最近更新 更多