Testing React Components
In this page:
Testing Typed Props
Testing typed props means rendering a component with an object that must satisfy its declared Props interface, so passing a prop of the wrong type fails at compile time before the test even runs.
Example: Testing Typed Props
import React from "react";
interface GreetingProps {
name: string;
}
function Greeting({ name }: GreetingProps): React.JSX.Element {
return <p>Hello, {name}</p>;
}
// render(<Greeting name="Ravi" />) requires name: string at compile time
export default Greeting;
Testing Rendered Text
Testing rendered text with something like screen.getByText(...) confirms the DOM output matches what a user would actually see, independent of the component's internal typed state.
Example: Testing Rendered Text
import React from "react";
function Message(): React.JSX.Element {
return <p>Welcome!</p>;
}
// screen.getByText("Welcome!") confirms the rendered DOM output
export default Message;
Typing Event Handlers
Typing event handlers passed to a component — e.g. onClick: (event: React.MouseEvent) => void — lets the test call the handler with a realistic, type-checked synthetic event instead of an untyped stub.
Example: Typing Event Handlers
import React from "react";
interface ButtonProps {
onClick: (event: React.MouseEvent) => void;
}
function Button({ onClick }: ButtonProps): React.JSX.Element {
return <button onClick={onClick}>Click</button>;
}
export default Button;
Testing Component State
Testing component state after a user interaction (like a click) verifies the component's internal state updated correctly, which in a typed component means the state shape itself is checked against its declared type.
Example: Testing Component State
import React, { useState } from "react";
function Counter(): React.JSX.Element {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
// after fireEvent.click, expect(count text).toBe("1")
export default Counter;
Testing Component Props and Callbacks
Testing that a component both renders its typed props correctly and invokes its typed callback props with the right arguments verifies the full typed contract between a component and its parent, not just one side of it.
Example: Testing Component Props and Callbacks
import React from "react";
interface FormProps {
onSubmit: (value: string) => void;
}
function Form({ onSubmit }: FormProps): React.JSX.Element {
return <button onClick={() => onSubmit("data")}>Submit</button>;
}
export default Form;
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: