Article thumbnail

Using spies in React and Typescript



Let's understand the common use cases for jest.spy API when testing React and TypeScript code. We'll listen to function calls!


I'm 100% sure that you've had a situation where you needed to pass your function as a parameter to another function or React component.

How to test such a code? How to verify that after clicking on some UI element your function was called with specific parameters and a specific/finite number of times? These questions can be answered by spies.

Testing TypeScript code with spies

Let's look at the map function written in an earlier lesson:


We need to write a test that will verify:

  • With what arguments the function was invoked
  • The number of function calls


The statement jest.fn() creates a spy object. Then, with the help of the mockImplementation method - we define the implementation of the callback passed to the maps.

Then, we check one by one:

  • That the number of callback calls is equal to the number of passed elements
  • The fact that on each call there were passed sequentially (element | index | array)

Testing React components with spies

The situation with testing callbacks passed to React components is almost the same.

However, sometimes we need to take into account asynchronicity. Take a look at the gif below - we will test such a component.


That's our ProgressCircle component

We'll be able to call this component in following way:


After a minimum of 10 seconds (because it depends on the load of the browser) the callback called onEnd will be called.


Everything is the same as before except for one change. Namely, we used the strange notation await waitFor.

Due to the fact that inside the ProgressCircle component, an interval is running every certain period of time, there may be a situation when we call expect before the callback onEnd was called. It's because intervals in JavaScript are async code.

Therefore, using the waitFor call, we will wait a while (about a second by default). This time is enough for onEnd to be called and will make our test green.

You can find all tests for ProgressCircle under this commit

See the documentation for more information about waitFor.


I hope you understood how to test callbacks in different situations. It is worth adding that so far it is only half-used. You will see how else you can use spies in the next lessons.

If you enjoyed it, be sure to visit us on Linkedin where we regularly upload content from programming.

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.


Add your honest opinion about this article and help us improve the content.

created: 10-04-2023
updated: 10-05-2023