Integration testing
- React course
- Advanced
- Lesson 45/56
- 4 min
Learn to test several components together.
Integration testing
Integration testing runs several components together and verifies real interaction. React Testing Library's render puts a component into the DOM; you query with screen.
Use fireEvent.click to click a button and screen.getByText to find the result. Tests behave like a user: they look at output, not internals.
The file is named Button.test.jsx; the runner finds it automatically.
fireEvent and user interaction
fireEvent simulates DOM events. fireEvent.click(element) mimics a click, fireEvent.change(input, { target: { value: '...' } }) mimics typing.
For more realistic behaviour use @testing-library/user-event; it also handles keyboard and focus details.
Among queries getByRole is the most robust; it finds by accessible role and name.
Practice Write the Button test
Write the contents of Button.test.jsx. Render <Button label="Save" /> with render, find it with screen.getByText('Save') and assert with expect(...).toBeInTheDocument(). Use test('shows label', () => {}).
Starter code
// Write the Button test hereSample solution
import { render, screen } from '@testing-library/react';
import Button from './Button';
test('shows label', () => {
render(<Button label="Save" />);
expect(screen.getByText('Save')).toBeInTheDocument();
});Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is the best query method in integration testing?
- Find visible text with screen.getByText Correct answer
- Read internal state via componentRef
- Search classes with querySelector
- Print with console.log
Explanation: You should look at visible text like a user.
2 Fill in the blank: click a button in a test
import { render, screen, fireEvent } from '@testing-library/react';
fireEvent.____(screen.getByText('Increment'));
import { render, screen, fireEvent } from '@testing-library/react';
fireEvent.click(screen.getByText('Increment'));
Explanation: Use fireEvent.click for clicks.
3 Match testing concepts
| Term | Meaning |
|---|---|
render |
Puts into DOM |
screen |
Runs queries |
fireEvent |
Simulates events |
getByRole |
Finds by accessible role |