JEST: how to stub a method which is been called in constructor of the class

Viewed 1378

This how a example looks like:

export class ABC {
  constructor() {
    this.method1();
  }

  method1() {
    console.log();
  }
}

Assume that there are some calls to external methods in method1 which are stopping the code to go forward. I don't want to go inside the method1.

Now the problem is when I do this:

describe('test cases!', () => {
  let abc: ABC;
  beforeEach(() => {
    spyOn(abc, 'method1').and.stub();
    abc = new ABC();
    jest.resetAllMocks();
  });
});

It's throwing error.

After the class initialisation I can't put the spyOn. Any idea guys?

Thanks for help.

2 Answers

method1 exists on ABC.prototype and you can spy on it and replace the implementation before constructing a new instance of ABC:

class ABC {
  constructor() {
    this.method1();
  }
  method1() {
    throw new Error('should not get here');
  }
}

test('ABC', () => {
  const spy = jest.spyOn(ABC.prototype, 'method1');  // spy on the method of the prototype
  spy.mockImplementation(() => {});  // replace the implementation
  const abc = new ABC();  // no error
  expect(spy).toHaveBeenCalled();  // SUCCESS
})

To build upon @brian-lives-outdoors answer, I use the following:

describe('test cases!', () => {
  beforeEach(() => {
    ABC.prototype.abc = jest.fn((data) => { result: 'some mock here', data)
    abc = new ABC();
  });
  afterEach(() => {
    ABC.prototype.abc.mockRestore()
  })
});
Related