Sometimes, we want to use Jest to spy on a method call with JavaScript.
In this article, we’ll look at how to use Jest to spy on a method call with JavaScript.
How to use Jest to spy on a method call with JavaScript?
To use Jest to spy on a method call with JavaScript, we call the spyOn method.
For instance, we write
const spy = jest.spyOn(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();
in our test to call spyOn to add a spy to the Component‘s methodName instance method.
The we call the methodName method on the component.
And we check if it’s called with with toHaveBeenCalled.
Conclusion
To use Jest to spy on a method call with JavaScript, we call the spyOn method.