circuit

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:

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!




Continue Learning