繁体   English   中英

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

[英]node ts-jest spyOn method does not match overload

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

impl.ts

export const dependency = () => {}

索引.ts

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

消费者.ts

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

消费者.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', () => {});
})

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

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

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

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

而不是这个

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

愚蠢的错误,希望它在未来对其他人有所帮助。 我的收获是,如果您遇到没有意义的类型错误,请确保检查所有涉及的变量的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM