问题
I am having issues when testing that the original method (from the base class), is called with some parameters, when testing an extended class. The class that I want to test is:
// 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
);
}
}
And basically, I would want to mock super.get()
to assert that when ApiDataSource.get()
is called, the super
method is called with the authorization parameters.
Something like:
// 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"})
});
Any idea how to do that? have tried jest.mock()
jest.spyOn
and so on and I can't seem to get it...
CodeSandbox: https://codesandbox.io/s/example-test-api-data-source-6ldpk?file=/src/ApiDataSource.test.ts
回答1:
You can use jest.spyOn(object, methodName) to create a mock function for RESTDataSource.prototype.get
method.
E.g.
ApiDataSource.js
:
import { RESTDataSource } from 'apollo-datasource-rest';
export default class ApiDataSource extends RESTDataSource {
constructor() {
super();
this.baseURL = 'test';
}
async get(path, params = {}, init = {}) {
return super.get(
path,
{
...params,
app_id: 'test app id',
app_key: 'test app key',
},
init
);
}
}
ApiDataSource.test.js
:
import { RESTDataSource } from 'apollo-datasource-rest';
import ApiDataSource from './ApiDataSource';
describe('65391369', () => {
test('adds the authorization parameters to the get call', async () => {
const mockedSuperGet = jest.spyOn(RESTDataSource.prototype, 'get').mockResolvedValueOnce('fake data');
const apiDataSource = new ApiDataSource();
await apiDataSource.get('test');
expect(mockedSuperGet).toHaveBeenCalledWith('test', { app_id: 'test app id', app_key: 'test app key' }, {});
mockedSuperGet.mockRestore();
});
});
unit test result:
PASS examples/65391369/ApiDataSource.test.js (5.273 s)
65391369
✓ adds the authorization parameters to the get call (4 ms)
------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
ApiDataSource.js | 100 | 100 | 100 | 100 |
------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 6.28 s
来源:https://stackoverflow.com/questions/65391369/jest-mock-method-of-base-es6-class-super-method-when-testing-extended-class