React - Testing (In-browser)
Overview
Estimated time: 20–30 minutes
This page introduces testing concepts and shows a tiny, in-browser assertion harness to validate component behavior without external tools.
Learning Objectives
- Understand the goal of component testing.
- Run simple PASS/FAIL assertions against components in the browser.
Try it: Mini Test Harness
View source
function assert(name, condition){
const el = document.getElementById('results');
const li = document.createElement('li');
li.textContent = `${condition ? 'PASS' : 'FAIL'} - ${name}`;
li.style.color = condition ? 'limegreen' : 'salmon';
el.appendChild(li);
}
function Greeter({ name }){ return <span>Hello, {name}!</span>; }
function runTests(){
const root = document.getElementById('sandbox');
ReactDOM.createRoot(root).render(<Greeter name="World" />);
assert('renders greeting', root.textContent.includes('Hello, World!'));
}
Syntax primer
- Assertions: Verify a condition and report PASS/FAIL.
- Rendering for tests: Render into a dedicated sandbox container.
Common pitfalls
- Don’t rely on implementation details; test visible behavior whenever possible.
Exercises
- Add another test to check that changing the prop updates the text.
- Write a small helper to clear the sandbox between tests.
Checks for Understanding
- What should component tests focus on?
- Why render into a fresh sandbox for each test?
Show answers
- Observable behavior and outputs rather than implementation details.
- To avoid state leakage between tests and ensure isolation.