Web Unit 3 Sprint 9 - Class Components & Testing

Module 4: Testing Web Applications

In this module, you'll learn about testing web applications using React Testing Library and Jest. You'll understand how to write effective tests for React components, custom hooks, and user interactions.

Testing is a crucial aspect of building reliable and maintainable React applications. By implementing a comprehensive testing strategy, you can catch bugs early, ensure your components behave as expected, and have confidence when refactoring or adding new features.

We'll focus on modern testing practices that emphasize testing behavior over implementation details, using tools like React Testing Library that encourage accessibility and user-centric testing approaches.

Learning Objectives

Testing React applications typically involves several types of tests:

React Testing Library is designed around the principle of testing components the way users actually use them, focusing on:

Content

React Testing Library

Key Concepts of React Testing Library

  • Testing Philosophy: Test the way users interact with components
  • Queries: Methods for finding elements in the rendered output
  • Firing Events: Simulating user interactions like clicks and keyboard input
  • Assertions: Making sure the component renders and behaves as expected
  • Setup: Using render, cleanup, and other utilities

Testing Output on Props Change

Testing Component Updates

  • Rerendering: Using rerender to update props between tests
  • Assertions: Verifying that components update correctly when props change
  • Testing Props: Checking that components use props values correctly
  • Testing Class Components: Using ReactTestUtils.act() for class component updates

Test lifecycle hooks

Testing with Lifecycle Hooks

  • Setup and Teardown: Using beforeEach, afterEach, beforeAll, afterAll
  • Mocks and Spies: Creating and resetting mocks between tests
  • State Management: Testing components with complex internal state
  • Testing useEffect: Verifying side effects in functional components

Creating asynchronous tests

Asynchronous Testing Techniques

  • waitFor: Waiting for elements to appear or disappear
  • Async/Await: Using async test functions for cleaner code
  • Mocking API Calls: Using jest.mock to mock fetch or axios
  • Testing Loading States: Verifying loading indicators appear and disappear
  • Error Handling: Testing how components handle API errors

Practice Activities

Additional Resources