0
0
ReactHow-ToBeginner · 3 min read

How to Render Component in Test in React: Simple Guide

To render a React component in a test, use the render function from @testing-library/react. This function mounts the component so you can check its output or behavior in your test code.
📐

Syntax

The render function is imported from @testing-library/react. You call render(<Component />) to mount the component in a virtual DOM for testing.

It returns an object with utilities like getByText to query the rendered output.

javascript
import { render } from '@testing-library/react';

const { getByText } = render(<Component />);
💻

Example

This example shows how to render a simple Hello component and check if it displays the correct text.

javascript
import React from 'react';
import { render, screen } from '@testing-library/react';

function Hello() {
  return <h1>Hello, world!</h1>;
}

test('renders Hello component', () => {
  render(<Hello />);
  const heading = screen.getByText('Hello, world!');
  expect(heading).toBeInTheDocument();
});
Output
Test passes if 'Hello, world!' is found in the rendered output.
⚠️

Common Pitfalls

  • Not importing render from @testing-library/react causes errors.
  • Trying to test without rendering the component first will fail because there is no output.
  • Using deprecated testing methods like ReactDOM.render in tests is discouraged.
  • Not wrapping components with required context providers can cause tests to fail unexpectedly.
javascript
/* Wrong way: missing render */
// expect(screen.getByText('Hello')).toBeInTheDocument(); // Fails because component not rendered

/* Right way: */
import { render, screen } from '@testing-library/react';

render(<Hello />);
expect(screen.getByText('Hello')).toBeInTheDocument();
📊

Quick Reference

Use these steps to render and test React components:

  • Import render and screen from @testing-library/react.
  • Call render(<YourComponent />) inside your test.
  • Use screen.getByText or other queries to find elements.
  • Assert expected output with expect.

Key Takeaways

Use the render function from @testing-library/react to mount components in tests.
Always render the component before querying its output in your test.
Use screen queries like getByText to find elements in the rendered output.
Avoid legacy methods like ReactDOM.render for testing React components.
Wrap components with necessary providers if they depend on context.