React testing overview

Khanh Nguyen • 17 February 2023 • 

ReactJsUnit TestingReact Testing Library

React testing fundamentals

React help simplify building a web application by establish a contract with developers that render output of React components is entirely derived from data provided.

The only way to change rendered output is by chaging the data provided.

That was great news for those who wish to write tests for React applications.

Over simplified idea of testing react

Create testable components

Ideally, a React component should be design in a way that's testable, which should ensure extracting application logic outside of components.

When testing, we focus mostly on#

Major parts of a React component

Barries to Testability#

Testing component rendering

Required tools#

React Testing Library query functions basic and examples#

Query Functions#

React Testing Library Query Functions

What are we testing#

Extracting component out of its logic and state

Rendering#

Nested element selecting example
Nested element selecting example

Testing Asynchronous Rendering#

There's primary 2 methods to achieve this expected behavior

Be careful with them both, and remember that they return a promise.

Snapshot testing#

Best suit for some specific cases that we're sure the rendered component should not be change over time. Jest provide 2 common function to achieve this:

Snapshot testing example

When the test execute later, it'll compare with the existing value to determine if the test should be fail or not. This kind of tests are usually used with react-test-renderer in order to serialize result that can be store as string.

User Interaction#

userEvent#

Tried to resemble how user interact with your application, simulate what happen in a browser.

userEvent API example

fireEvent#

Simply allows us to trigger DOM events on DOM elements. It is not an accurate representation of what happens when a human uses a browser. Therefore, it's simple.

fireEvent API example

Khanh Nguyen

Web developer & .Net lover