节点 ts-jest spyOn 方法不匹配重载

node ts-jest spyOn method does not match overload

我正在尝试将 Jest 与 ts-jest 结合使用来为 nodeJS 服务器编写单元测试。我的设置与以下非常相似:

impl.ts

export const dependency = () => {}

index.ts

import { dependency } from './impl.ts';
export { dependency };

consumer.ts

import { dependency } from '../impl' <- importing from index.ts
export const consumer = () => {
  try {
   dependecy();
   return true;
  } catch (error) {
    return false;
  }
}

consumer.test.ts

import * as dependencies from '../impl'
import { consumer } from './consumer'
const mockDependency = jest.spyOn(dependencies, 'depenedncy');
describe('function consumer', function () {
  beforeEach(function () {
     mockDependency.mockReturnValueOnce(false);
  });

  test('should return true', () => {});
})

这只是玩具代码,但实际的导出/导入/测试文件遵循类似的结构。我在这些方面遇到打字稿错误:

TS2769: No overload matches this call. 具体来说,被监视的方法不是依赖项导入重载的一部分,所以我无法将其删除。我在不同的测试文件中做同样的事情,没有任何问题。有人知道如何解决打字问题吗?

问题出在依赖函数本身的类型上。 return 值键入不正确,这就是导致 Typescript 错误的原因。基本上我有这个:

export const dependency: Handler = () => {
  return () => {} <- is of type Handler
}

而不是这个

export const dependency = (): Handler => {
  return () => {} <- is of type Handler
}

愚蠢的错误,希望对以后的其他人有所帮助。我的收获是,如果你有一个没有意义的类型错误,请确保你检查所有涉及的变量的类型。