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
- Testing them separately will help me organize the test code better, and
- In one case
helper
calls code I don't want to unit test -- I don't want to try to mock out everything in thehelper
, I just want to verify that the helper is called.
You can do something like this :
Example.js :
Example.test.js :