Categories
JavaScript Answers

How to use Jest to spy on a method call with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *