用Jest测试TypeScript:“没有重载匹配此调用”

问题描述 投票:0回答:1

我正在使用Jest测试Apollo服务器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:没有重载匹配此呼叫

get中的jest.spyOn(dataSource,'get')

我得到

enter image description here

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)

感谢您提供任何线索!

我正在使用Jest测试Apollo服务器RESTDataSource。我的应用程序是用TypeScript编写的。我的类CDCDataSource扩展了抽象类RESTDataSource,它本身扩展了...

typescript unit-testing jestjs apollo apollo-server
1个回答
0
投票

您正在尝试访问protected方法。

© www.soinside.com 2019 - 2024. All rights reserved.