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.
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With