3 dimensions to test React code
We can test our React code through 3 dimensions
- Pure UI rendering
- Internal states of UI
- UX, what happens while the user is interacting on our UI
Pure UI rendering
This is probably the most common way to test React code.
To test if our UI gets displayed correctly, we can use snapshot testing, which compares the current render result with the latest one, a snapshot file represented in JSON structure. If they don’t match, you can either fix your react code or update the snapshot file which means you confirm this change
Example test code:
When it runs for the first time, it will create the snapshot file
Internal states of UI
It’s easiest to test pure functions, just write unit tests to test the output for specific input. But it’s difficult to test the internal state of UI. They couldn’t be tested directly. In the old days, we can only rely on e2e testing by checking the UI elements to spy out the internal states.
Now, since hook
comes to the scene, we can encapsulate those internal states, especially with complex data processing, as React hooks and then test them directly, as if we test pure functions
For example, we have a hook named useCounter
We can test it with @testing-library/react-hooks
You can even update the hook’s state as you do in a real application
UX
While snapshot testing is for one-time rendering, static and non-interactive, we turn to e2e testing to ensure everything goes well in users’ real usage. We want to test from the perspective of users, treating our UI as a black box and focusing on the function, not implementation details.
Currently, the prevalent e2e testing tool is Cypress
But e2e tests cost a lot of time to run and are failure-prone while their test cases are difficult to write.
Now, we have another choice — DOM Testing Library. You can consider it as a lightweight alternative. It renders your UI in Node.js rather than a browser, leveraging DOM APIs provided by jsdom
. With it, you can mimic user actions and check the UI state before and after.
Example code:
You can see the full example on the official website