Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 91

Testing Components with State, Props, and Context

Recommended resources

Hello! Welcome back to our module on Testing, Building, and Deploying.

In the previous lesson, we mastered the art of unit testing presentational components. We learned how to render a component in isolation, provide it with props, and assert that its output matches our expectations. This is a crucial skill for ensuring the individual bricks of our application are solid.

Today, we're moving up a level from unit tests to integration tests. The goal of this lesson is to learn how to write integration tests for components that involve state, props, and context. We'll shift our focus from testing components in isolation to verifying that they work together correctly to create dynamic and interactive user experiences.

1. From Unit to Integration Testing: A Shift in Perspective

In React, the line between unit and integration testing can be blurry, but the distinction is important.

  • Unit Test: Verifies a single, isolated piece of code (e.g., a pure presentational component).
  • Integration Test: Verifies that several "units" work together as expected. In React, this often means rendering a component that manages its own state or interacts with other components, hooks, or context.

For many React applications, integration tests provide the most confidence. They test components closer to how a real user would experience them.

To understand this philosophy better, let's start with a brief video that explains why we lean towards integration tests when testing React applications.

React Testing for Beginners: Start Here!

This short segment from Programming with Mosh's tutorial explains the rationale behind integration testing in React. It introduces the 'test pyramid' and clarifies why testing component behavior, rather than implementation details, leads to more robust tests.

Please watch from 21:01 to 24:15. Focus on the conceptual difference between unit and integration tests in a React context and the idea of testing what the application does, not how it is implemented.

As the video highlighted, we want our tests to simulate user behavior and verify the outcome. This brings us to our first topic: testing components with internal state.


2. Testing Components with Internal State (useState)

When a component has internal state, its output is no longer just a function of its props. User interactions can trigger state updates, which in turn cause the component to re-render with new UI. A good integration test will cover this entire flow:

  1. Arrange: Render the component in its initial state.
  2. Act: Simulate a user event (like a click or a key press).
  3. Assert: Verify that the UI has updated correctly as a result of the state change.

To simulate user events, we use the @testing-library/user-event library, which we installed in the previous module. It provides a more realistic simulation of user interactions than the lower-level fireEvent API.

Example 1: A Simple Counter

Let's see this in action with a classic Counter component that uses useState.

TypeScript/React Testing: Components, Hooks, Custom Hooks, Redux and Zustand

This video from Jack Herrington provides a concise demonstration of testing a simple Counter component. It's a perfect first example of testing a component with state.

Watch from 11:43 to 13:58. Notice the clear Arrange-Act-Assert pattern: Arrange: The component is rendered, and initial elements are queried. Act: fireEvent.click is used to simulate a button press (note: modern practice prefers userEvent.click). Assert: The test checks if the displayed count has been updated from 0 to 1.

The key takeaway is that we don't inspect the state variable itself. We verify the state change indirectly by checking if the DOM has updated as expected.

Example 2: Testing Conditional Logic with State

Now for a more realistic example: a TermsAndConditions component where checking a box enables a 'Submit' button. This involves a boolean state that conditionally applies a disabled attribute.

React Testing for Beginners: Start Here!

This is a fantastic, practical example from Programming with Mosh. It shows how to test a component where a user interaction (checking a box) changes state, which then affects another element (a button).

Please watch from 52:59 to 01:02:10. This is a critical section. Pay close attention to: The initial state test: asserting the checkbox is unchecked and the button is disabled. Setting up userEvent with userEvent.setup(). Using await user.click(checkbox) to simulate the interaction. The final assertion: expect(button).toBeEnabled().

This test gives us high confidence that the core functionality of our component works. We've tested the initial state and the state transition triggered by a user.

Test your understanding!

Imagine an ExpandableText component that truncates long text and shows a "Show More" button. Clicking it reveals the full text and changes the button to "Show Less". Clicking "Show Less" collapses the text again.

Outline the Arrange, Act, and Assert steps for a test that verifies the text collapses correctly.

Show answer
  1. Arrange:

    • Render the ExpandableText component with a long text prop.
    • Find the "Show More" button.
    • Click the "Show More" button to expand the text (this is part of the setup for this specific test).
  2. Act:

    • Find the "Show Less" button.
    • Click the "Show Less" button.
  3. Assert:

    • Assert that the full text is no longer in the document.
    • Assert that the truncated text is in the document.
    • Assert that the button now reads "Show More".

This approach ensures you test a full cycle of user interaction. The solution for this exact problem is covered in the same video from Mosh at 01:02:10.


3. Testing Communication: Props as Callbacks

A very common integration pattern in React is passing functions as props from a parent to a child component. The child then calls this function in response to an event, enabling child-to-parent communication.

To test this, we need to verify that the function prop is called when the user interacts with the child component. We can do this using a "mock function" provided by Vitest: vi.fn().

vi.fn() creates a spy that keeps track of when it's called, how many times, and with what arguments.

Let's examine how to test a UserCard component that takes an onEdit function prop.

Testing React Components with TypeScript

This section from Steve Kinney's article on testing with TypeScript provides a clear, text-based example of testing a callback prop. It's a perfect illustration of using a mock function to verify child-to-parent communication.

Please read the section titled Testing Props and Component APIs. Focus on the UserCard.tsx component and the UserCard.test.tsx file, specifically the test case that starts with it('calls onEdit with correct user data', ...). Note how vi.fn() is created and passed as a prop, and how toHaveBeenCalledWith() is used for the assertion.

The pattern is straightforward and powerful:

  1. Arrange: Create a mock function with const mockFunction = vi.fn().
  2. Arrange: Render your component, passing mockFunction as a prop.
  3. Act: Simulate the user event that should trigger the callback.
  4. Assert: Use expect(mockFunction).toHaveBeenCalled() or expect(mockFunction).toHaveBeenCalledWith(...) to verify the interaction.

4. Testing Components Consuming Context

What happens when a component's state comes from a global provider, like one created with React.createContext or used by libraries like Redux or Zustand? If you try to render a component that uses useContext in a test without a matching provider, your test will fail.

The solution is to wrap the component under test with the necessary Provider during rendering.

The renderWithProviders Pattern

For any application that uses context extensively, it's a best practice to create a custom render function that automatically wraps components in the required providers. This ensures consistency and reduces boilerplate in your tests.

The official Redux documentation has the canonical guide on how to create this utility. Even if you're not using Redux, the principle is the same for any context provider.

Writing Tests

The Redux documentation provides an excellent explanation of the renderWithProviders utility function. This is a fundamental pattern for integration testing in any medium-to-large React application.

Please read the section Setting Up a Reusable Test Render Function. You don't need to memorize the code, but understand its purpose: it's a custom version of RTL's render that creates a fresh Redux store for each test and wraps the rendered UI in a <Provider>. This ensures your tests are isolated from each other.

With a helper like renderWithProviders, testing a context-dependent component becomes much cleaner. You can even pass a preloadedState to your custom render function to test how your component behaves with specific initial data in the store.

Seeing it in Practice: Redux and Zustand

Let's watch how this pattern is applied to test components connected to two popular state management libraries, both of which use context under the hood.

TypeScript/React Testing: Components, Hooks, Custom Hooks, Redux and Zustand

Jack Herrington's video demonstrates testing components connected to both Redux and Zustand. It vividly illustrates why a clean state is crucial for each test and how to achieve it.

Watch the section on Redux (22:15 - 26:22) and Zustand (26:11 - 29:00). The key takeaway for both is the problem that arises from a shared, global state and the solution: ensuring each test runs with a fresh, predictable state by either creating a new store or resetting the existing one before each test.

The core principle is test isolation. Global state is a major source of flaky tests that pass or fail depending on the order they run. By creating a new store or resetting the state before each test (beforeEach), you guarantee that every test starts from a clean, predictable slate.


Conclusion

Today we've bridged the gap between unit and integration testing. You now have the tools to test the dynamic behavior of your components, ensuring that state changes, props, and context all work together as intended.

Key Takeaways:

  • Integration tests give confidence by testing how units of your application work together, closely resembling real user flows.
  • Test state changes indirectly by simulating a user event with @testing-library/user-event and then asserting that the DOM has updated as expected.
  • Verify child-to-parent communication by passing a mock function (vi.fn()) as a prop and asserting that it was called correctly after a user interaction.
  • Test context-dependent components by wrapping them in a <Provider> with a mock value or store. Using a custom renderWithProviders helper is the recommended pattern for this, ensuring test isolation.

Preview of the Next Lesson:
We've had a taste of simulating user actions with user-event. In the next lesson, "Simulate user interactions like clicks and input typing using @testing-library/user-event," we will take a much deeper dive into this powerful library. We'll explore how to handle complex form inputs, keyboard interactions, and more, which will fully equip us to test the most interactive parts of our applications.