我正在使用Jest测试Apollo服务器RESTDataSource
。我的应用程序是用TypeScript编写的。我的类CDCDataSource
扩展了抽象类RESTDataSource,后者本身也扩展了抽象类DataSource
。 RESTDataSource
具有方法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')
上
我得到
在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,它本身扩展了...
您正在尝试访问protected
方法。