使用模拟进行测试时如何更新打字稿的签名

时间:2019-04-21 21:28:16

标签: typescript mocking jestjs

我正在开玩笑地模拟具有此签名的方法的实现

(arg1: string, arg2: string, arg3: callback)
(arg1: string, arg3: callback)

并且我想通过模仿实现直接在我的测试中调用arg3

func.mockImplementation((arg1: string, arg2: string, arg3: callback) => {
  const actualCallback = arg2 // we know we are using the second case here.
  actualCallback()
})

但是打字稿给我一个错误。嘲笑函数签名时如何跳过打字稿检查?

1 个答案:

答案 0 :(得分:1)

您可以通过以下两种方式之一进行操作。

  1. 您必须以不同的方式键入第二个参数,以反映此功能结合了前两个类型签名。
func.mockImplementation((arg1: string, arg2: string | callback, arg3: callback) => {
  const actualCallback = arg2 as callback // Explicitly tell TS what type it is.
  actualCallback()
})
  1. 只需用“ // @ ts-ignore”注释忽略该错误即可。
func.mockImplementation((arg1: string, arg2: string, arg3: callback) => {
  const actualCallback = arg2
  // @ts-ignore
  actualCallback()
})