

👁 Spying
jest.spyOn( PROTOTYPE_OR_CLASS, METHOD_NAME )
Spying is to observe calls made to a method without changing the method itself.
Spy on a Method
Let’s say you have a class in a module:

This is how you can spy on instance and static methods:

If the spy is assigned to a variable, you can also access it via a variable (instead of via the method being spied on):

Here are some of the Jest matchers you can use with spyOn:

Spy on a Built-in Method
Built-in methods are not safe from spies either. You can spy on them like this:

Change the Implementation of a Method Being Spied on
This is called ‘mocking’, as we can fake the behavior of a method this way, thereby ‘mocking’ the method.

You can replace the contents of a method also by using jest.fn()
👻 Mocking
METHOD = fn( () => {...} )
You can temporarily replace the contents of a method with Jest mocks.
Mock a Method
Let’s say you have a class in a module:

You can replace the contents of its methods this way:

Mock a Built-In Method
Replace .addEventListener method with a mock one:

Conclusion
We have seen two approaches to keeping tabs on the methods in our code. You can use jest.spyOn for a non-intrusive way to record calls. Alternatively, you can use jest.fn to replace a method entirely with a fake version of it, which is called ‘mocking’.
Happy coding!
Further Reading
Discover more articles on similar topics across our network
The Technical Foundations behind Effective Healthcare Website Design
Stackademic
Claude Meetings Beta in Google Meet Pushes Developer Marketing Battle With Gemini Note-Taking
Anthropic's in-call agent can draft artifacts live while Google Meet's native Gemini features target the same workflow, setting up a competitive story for B2B AI distribution.
Comments
Loading comments…