Jest Spies and Mocks in Explained via Examples

Make your JavaScript tests deeper, leaner, and faster with these two Jest methods

Photo by Petri Heiskanen on Unsplash

TL;DR

👁 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:

image

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

image

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

image

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

image

Spy on a Built-in Method

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

image

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.

image

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:

image

You can replace the contents of its methods this way:

image

Mock a Built-In Method

Replace .addEventListener method with a mock one:

image

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!

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics