【问题标题】:Testing TypeScript with Jest: "no overload matches this call"用 Jest 测试 TypeScript:“没有重载匹配这个调用”
【发布时间】:2020-09-13 11:57:02
【问题描述】:

我正在使用 Jest 测试 Apollo Server RESTDataSource。我的应用程序是用 TypeScript 编写的。我的类CDCDataSource 扩展了抽象类RESTDataSource,它本身扩展了抽象类DataSourceRESTDataSource 具有 get 方法,它允许您从外部 REST 数据源中提取数据。这是我希望模拟的方法,因为我希望模拟外部数据源。

  protected async get<TResult = any>(
    path: string,
    params?: URLSearchParamsInit,
    init?: RequestInit,
  ): Promise<TResult> {
    return this.fetch<TResult>(
      Object.assign({ method: 'GET', path, params }, init),
    );
  }

但是,当我尝试使用 Jest 的 spyOn 模拟此方法时 - 遵循此处的第二个答案:Jest: How to mock one specific method of a class -

import CDCDataSource from '../CDCDataSource';

test('Test', () => {
    let dataSource = new CDCDataSource();
    let spy = jest.spyOn(dataSource, 'get').mockImplementation(() => 'Hello');
    expect(dataSource.get()).toBe('Hello');


但是,我收到 TypeScript 错误

TS2768:没有重载匹配此调用

getjest.spyOn(dataSource,'get')

我得到了

get

expect(dataSource.get()).toBe('Hello');

所以问题的一部分似乎是这是一个保护方法——我不清楚如何测试这个方法以便能够模拟 API。

我的tsconfig.json

{
  "compilerOptions": {
    "target": "ES6",
    "lib": [
      "esnext",
      "dom"
    ],
    "skipLibCheck": true,
    "outDir": "dist",
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "sourceMap": true,
    "alwaysStrict": true,
  },
  "exclude": [
    "node_modules"
  ]
}

这是一个 Node Apollo Server 项目(使用 Node 12.14.0 和 TypeScript 3.8.3)

感谢您提供任何线索!

【问题讨论】:

    标签: typescript unit-testing jestjs apollo apollo-server


    【解决方案1】:

    您正在尝试访问protected 方法。

    如果您不想或无法重新架构您的课程,您可以使用ts-ignore 来抑制错误。

        // @ts-ignore`
        let spy = jest.spyOn(dataSource, 'get').mockImplementation(() => 'Hello');
    

    或者您可以扩展原始类,使用仅用于测试的类,该类将具有仅代理受保护方法的公共方法。

    test('Protected method',()=>{
    
      class Test extends OriginalClass {
        testProtected(){
          super.protectedMethod()
        }
      }
      let dataSource = new Test();
      let spy = jest.spyOn(dataSource, 'testProtected').mockImplementation(() => 'Hello');
    })
    

    【讨论】:

    • 编写测试时最好使用@ts-expect-error
    • 我不能重新设计这个类,因为它不是我的——它来自 Apollo。我会按照代理的方法...
    猜你喜欢
    • 2020-06-14
    • 2021-12-19
    • 1970-01-01
    • 2022-06-11
    • 2021-10-12
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多