Book Image

Simplify Testing with React Testing Library

By : Scottie Crump
Book Image

Simplify Testing with React Testing Library

By: Scottie Crump

Overview of this book

React Testing Library (RTL) is a lightweight and easy-to-use tool for testing the document object model (DOM) output of components. This book will show you how to use this modern, user-friendly tool to test React components, reducing the risk that your application will not work as expected in production. The book demonstrates code snippets that will allow you to implement RTL easily, helping you to understand the guiding principles of the DOM Testing Library to write tests from the perspective of the user. You'll explore the advantages of testing components from the perspective of individuals who will actually use your components, and use test-driven development (TDD) to drive the process of writing tests. As you advance, you'll discover how to add RTL to React projects, test components using the Context API, and also learn how to write user interface (UI) end-to-end tests using the popular Cypress library. Throughout this book, you’ll work with practical examples and useful explanations to be able to confidently create tests that don't break when changes are made. By the end of this React book, you will have learned all you need to be able to test React components confidently.
Table of Contents (10 chapters)

Testing APIs with Cypress

In the previous section, we learned how to structure test code using the POM and custom commands design patterns. We also learned that we could use Cypress to interact with our application's API directly. In this section, we will build on the previous section's learnings by testing the API of the blog application previously introduced in the Cypress-driven development section.

The blog application accepts four API requests: a GET request to get all posts, a POST request to add a post, a POST request to get a single post, and a DELETE request to delete a post. First, we will test the GET request for all posts:

import fakePost from '../support/generateBlogPost';
  const post = fakePost()
 
const getAllPosts = () => cy.request('/api/posts').its('body.
posts');
const deletePost = (post) =>
  cy.request('DELETE', `/api/delete/${post.id}`, {
    id: post.id,
 ...