【发布时间】:2020-09-13 11:57:02
【问题描述】:
我正在使用 Jest 测试 Apollo Server 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)
感谢您提供任何线索!
【问题讨论】:
标签: typescript unit-testing jestjs apollo apollo-server