Jest, the RTL, and Fixtures
Explore how to write effective tests for React components using Jest and the React Testing Library. Learn to create realistic test fixtures with faker.js and uuid, configure the testing environment, and extend RTL's render method to simplify routing context setup. This lesson helps you build reliable, user-centric frontend tests for robust React applications.
We'll cover the following...
Jest is a JavaScript framework for writing, running, and structuring tests. It comes with all the tools needed to check code coverage, easily mock functions and imported functions, and write simple and great exceptions. The RTL is a library for actually testing React applications. It focuses on testing components from a user experience point of view rather than testing the implementation and logic of the React components themselves.
Note: When writing tests, we will often need to ensure that some values or variables meet certain conditions. When testing the Django application using
pytest, this was done usingassert. When working with Jest, the term changes from assertion to exceptions. When doing frontend testing with Jest, we are expecting the value to meet a condition. For example, if the user enters and clicks on a button that will reset a form, we expect the form to be reset after the click action is made on the button.
The RTL is not separated from Jest because we need both to write tests for our frontend application. Jest will help us write the testing blocks, while the RTL will provide tools to select components, render the components, and trigger common user events, such as clicking and typing. These tools are already installed by default when creating a React project, so there is no need to add other packages.
The ...