Jest Mocks and Spies

Learn how to use Jest mocks and spies to test that functions are called with the correct arguments.

When testing our code, we often want to ensure that a particular function was called or that it was called with the correct parameters. This is most often seen when a particular function calls other functions in a sequence in order to execute some business logic.

We may call an initialize function, for example, and this initialize function may call a number of REST services to load data.

When writing a test for our initialize function, we would want to ensure that all of the calls to REST services were called. To ensure that functions are called, we use Jest mocks or Jest spies.

Jest mocks

As an example of where we can use a Jest mock, consider the following class:

Get hands-on with 1200+ tech skills courses.