How to mock a Javascript instance method called by the constructor

28 views Asked by At

Is it possible to mock a Javascript instance method that is called by the constructor?

For example, give this design

class Example {
   constructor() {
      // other stuff
      helper();
      // other stuff
   }

   helper() {
      // ....
   }
}

Is there a way to write a unit test in Jest that verifies that the constructor calls helper (other than verifying that some specific line in helper ran)?

Normally, if I wanted to mock an instance method, I'd do something like this:

   e = new Example()
   e.helper = jest.fn()

But, in this case, helper will have been called before I can set up the mock.

I know that I can just test helper by calling the constructor, but

  1. Testing them separately will help me organize the test code better, and
  2. In one case helper calls code I don't want to unit test -- I don't want to try to mock out everything in the helper, I just want to verify that the helper is called.
1

There are 1 answers

0
Selaka Nanayakkara On

You can do something like this :

Example.js :

class Example{
  constructor() {
    this.someValue = this.helperFunction();
  }

  helperFunction() {
    // Some implementation details
    return 'Hello, World!';
  }
}

module.exports = Example;

Example.test.js :

const Example = require('./Example');

// Mock the helper function
jest.mock('./Example', () => {
  return {
    ...jest.requireActual('./Example'),
    helperFunction: jest.fn(),
  };
});

describe('Example', () => {
  it('should call helperFunction during construction', () => {
    // Arrange
    const myClassInstance = new Example();

    // Assert
    expect(Example.prototype.helperFunction).toHaveBeenCalled();
    // You can also check other expectations based on the specific behavior of your code
  });
});