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.
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.
- 1. Basics
Grouping the tests
The usage of describe and it
The best practices for naming tests
Types of tests
- 2. Mastering unit testing
Project and tests setup
Unit tests review
React component testing
Snapshot testing in React
Understanding stubs in testing
Understanding mocks in testing
Creating testing fixtures
Using spies in React and Typescript
Mocking environment variables
- 3. Mastering integration testing