【问题标题】:calling jest.spyOn "method name" parameter with a variable使用变量调用 jest.spyOn “方法名称”参数
【发布时间】:2022-01-11 17:28:13
【问题描述】:

使用 Typescript 和 Jest,我有一个用方法定义的类

export class myAPI {
   public someMethod(){...}
}

并想在其上调用 jest.spyOn,这对于像这样的直接调用效果很好

jest.spyOn(myAPI.prototype, 'someMethod')

但是当试图提供第二个参数方法作为变量时:

const theMethodName : string = 'someMethod'
jest.spyOn(myAPI.prototype, theMethodName)

我收到了Argument of type 'string' is not assignable to parameter of type 'FunctionPropertyNames<Required<myApi>>'.

如何将其类型转换为预期的类型?

【问题讨论】:

  • const string theMethodName = ... 不是 TypeScript。大概你实际上有const theMethodName: string = ... - 如果你刚刚做了const theMethodName = 'someMethod',那么类型将是'someMethod',你的第一个例子显示它是有效的,而不是string
  • 你是对的 - 我更正了代码......这也为我指出了解决方案 - 谢谢!

标签: typescript jestjs ts-jest


【解决方案1】:

确保变量没有显式键入为string,而是any 解决了它!

【讨论】:

  • 这真的解决了它,还是你只是掩盖了一个不同的问题?
  • 我相信它确实解决了它。在我稍微复杂的用例中,我使用test.each(arrayOfParams) 来动态运行多个测试。 spyOn 的参数在数组中定义为一个字符串,它不起作用 - 但显式任何它都起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
相关资源
最近更新 更多