【发布时间】:2021-03-31 03:13:10
【问题描述】:
在测试扩展类时,我在测试使用某些参数调用原始方法(来自基类)时遇到问题。我要测试的类是:
// ApiDataSource.js
import { RESTDataSource } from "apollo-datasource-rest";
export default class ApiDataSource extends RESTDataSource {
constructor() {
super();
this.baseURL = 'test';
}
//We add the authorization params to the get method
async get(path, params = {}, init = {}) {
return super.get(
path,
{
...params,
app_id: "test app id",
app_key: "test app key",
},
init
);
}
}
基本上,我想模拟 super.get() 以断言当调用 ApiDataSource.get() 时,使用授权参数调用 super 方法。
类似:
// ApiDataSource.test.js
import ApiDataSource from './ApiDataSource'
// ...
test("adds the authorization parameters to the get call", async () => ({
const class = new ApiDataSource();
await class.get("test");
expect(mockedSuperGet).toHaveBeenCalledWith("test", {app_id: "test app id", app_key: "test app key"})
});
知道怎么做吗?已经试过jest.mock()jest.spyOn等等,我似乎无法得到它......
代码沙盒: https://codesandbox.io/s/example-test-api-data-source-6ldpk?file=/src/ApiDataSource.test.ts
【问题讨论】:
-
当然,只是模拟/窥探
RESTDataSource.prototype.get? -
您能否提供一个关于如何做到这一点的示例@Bergi(基于上述代码)?
-
我手头没有,不,但请参阅他们的文档。你能不能edit你的问题包括你的尝试?
-
已经快速编译了这个@Bergi:codesandbox.io/s/example-test-api-data-source-6ldpk?file=/src/… jest.mock() 似乎有问题,但也许你明白了......还尝试用
jest.mock("apollo-datasource-rest", () => ({ RESTDataSource: jest.fn()})模拟整个班级或者其他什么,但也没有任何成功...... -
你不要嘲笑超类。继承的行为是行为的一部分。取而代之的是模拟合作者。
标签: javascript unit-testing jestjs apollo-server