Skip to content Skip to sidebar Skip to footer

Jest Mock Method Of Base ES6 Class (super Method) When Testing Extended Class

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: //

Solution 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

Post a Comment for "Jest Mock Method Of Base ES6 Class (super Method) When Testing Extended Class"