Simplify Testing with React Testing Library
eBook - ePub

Simplify Testing with React Testing Library

Scottie Crump

  1. 246 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Simplify Testing with React Testing Library

Scottie Crump

Detalles del libro
Vista previa del libro

Información del libro

A fast-paced, practical guide to helping you leverage React Testing Library to test the DOM output of componentsKey Features• Get to grips with React Testing Library and create tests that don't break with changes in implementation• Learn how to put RTL into practice by implementing it in real-world scenarios• Test apps to be more accessible and ensure your tests will work with actual DOM nodesBook DescriptionReact 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.What you will learn• Explore React Testing Library and its use cases• Get to grips with the RTL ecosystem• Apply jest-dom to enhance your tests using RTL• Gain the confidence you need to create tests that don't break with changes using RTL• Integrate Cucumber and Cypress into your test suite• Use TDD to drive the process of writing tests• Apply your existing React knowledge for using RTLWho this book is forThis book is for software engineers, quality engineers and React developers who want to learn about modern practices used for testing React components using the latest testing tool, RTL. Basic knowledge of React development is required to get the most out of this book.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Simplify Testing with React Testing Library un PDF/ePUB en línea?
Sí, puedes acceder a Simplify Testing with React Testing Library de Scottie Crump en formato PDF o ePUB, así como a otros libros populares de Computer Science y Quality Assurance & Testing. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.


Computer Science

Chapter 1: Exploring React Testing Library

React Testing Library is a modern tool for testing the UI output of React components. It abstracts a lot of boilerplate code, allowing you to write code that is easier to read, and allows you to test the code. The library encourages you to move away from testing implementation details, to avoid many false negative and false positive test cases. Instead, the library's API of tools makes it easy for you to write tests that simulate actual users' behaviors with your components, yielding confidence that the application works as expected for users. Also, because the library urges you to focus on the user when writing tests, you don't need to continuously update tests that fail when you refactor the code's implementation details. The React Testing Library allows you to write tests that fail when critical functionality unexpectedly changes, thus providing more value.
By the end of this chapter, you will understand what the implementation details are and the disadvantages they bring regarding maintenance and value in your test cases. For many years, it has been common for teams to test their components by focusing on the code's implementation details. Many teams still use this approach today. However, there are better ways to test the components that we will cover in this chapter. You will learn how to add confidence to your test case planning by understanding how to shift your thinking toward testing from the user's perspective. We will introduce you to the ideas behind the Document Object Model (DOM) Testing Library to ease the task of testing before transitioning to the primary focus, the React version of the library.
Next, you will learn about the Jest testing framework, tasked with executing and asserting our tests' output. Finally, you will learn how to install and use the jest-dom utility to enhance test assertions.
In this chapter, we're going to cover the following main topics:
  • Learning about the DOM Testing Library
  • Understanding the role of Jest in testing React applications
  • Learning about the advantages of using jest-dom to test React applications with Jest
  • Understanding the disadvantages of implementation detail-focused testing
The lessons of this chapter will set the foundation for understanding how you will use React Testing Library throughout this book to write better tests that focus on the user's perspective. The skills gained in this chapter will help whether you are new to writing tests for React applications or are an experienced tester looking for better ways to verify that your code works as expected.

Technical requirements

For the examples in this chapter, you will need to have Node.js installed on your machine. You can find the code examples for this chapter here:

Introducing the DOM Testing Library

The DOM Testing Library is a collection of tools created by Kent C. Dodds and numerous contributors to make our lives easier when our goal is to test our applications' UI from real users' perspectives. This section will give you an overview of how the library can help make testing efforts focused on users' perspectives a lot easier.

What is the DOM Testing Library?

The DOM Testing Library makes it easier to test the UI of applications like real users to gain confidence that the application works as expected for users. There are no methods to get the component's state value or directly invoke component methods.
The library encourages you to select DOM elements in ways that are available to all users. The library's API includes accessibility-focused query methods allowing you to interact with the DOM like users with disabilities who require tools such as screen readers or other forms of assistive technology to navigate applications. For example, say you want to select the following element in your test:
placeholder="first name..."
In the preceding code, we have an input element of type "text". You could select the input on the screen by its placeholder value of "First Name..." with the DOM Testing Library like so:
screen.getByPlaceholderText(/first name/i)
The getByPlaceholderText method is used from the screen object to select the DOM element by its placeholder value in the preceding code. The screen object allows you to select...


  1. Simplify Testing with React Testing Library
  2. Contributors
  3. Preface
  4. Chapter 1: Exploring React Testing Library
  5. Chapter 2: Working with React Testing Library
  6. Chapter 3: Testing Complex Components with React Testing Library
  7. Chapter 4: Integration Testing and Third-Party Libraries in Your Application
  8. Chapter 5: Refactoring Legacy Applications with React Testing Library
  9. Chapter 6: Implementing Additional Tools and Plugins for Testing
  10. Chapter 7: End-to-End UI Testing with Cypress
  11. Answers
  12. Other Books You May Enjoy