Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 487
PJ1405 Avatar asked Oct 23 '25 20:10

PJ1405


1 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
})
like image 165
Brian Adams Avatar answered Oct 26 '25 09:10

Brian Adams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!