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
- Use React Testing Library for testing React components
- Test output on props change
- Using test lifecycle hooks
- Creating asynchronous tests
Testing React applications typically involves several types of tests:
- Unit Tests: Testing individual components in isolation
- Integration Tests: Testing how components work together
- End-to-End Tests: Testing the entire application flow
React Testing Library is designed around the principle of testing components the way users actually use them, focusing on:
- Accessibility concerns
- User interactions rather than implementation details
- Finding elements by role, text, or label rather than test IDs or class names
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