Introduction
React testing is an important part of building and maintaining React applications. The tools we’re going to use are:
- Jest: A JavaScript testing framework, which provides us with tools to write assertions.
- React Testing Library: A set of helper functions for testing React components. It encourages best practices by making it difficult to write tests that break when you refactor your components.
First, you need to install Jest and React Testing Library. Here’s how you do it with npm:
npm install --save-dev jest @testing-library/react
Writing Your First Test
Let’s say you have a simple component like this:
// Greeting.js
import React from 'react';
const Greeting = ({ name }) => (
<h1>Hello, {name}!</h1>
);
export default Greeting;
To test this component, you might write a test like this:
// Greeting.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import Greeting from './Greeting';
test('renders greeting with name', () => {
render(<Greeting name="John" />);
expect(screen.getByText('Hello, John!')).toBeInTheDocument();
});
This test uses the render
function from React Testing Library to render the component, and then uses screen.getByText
to find the element with the text “Hello, John!”. The expect
function is from Jest, and toBeInTheDocument
is a Jest matcher from ‘@testing-library/jest-dom’.
Five Examples of Unit Tests
1. Testing Prop Changes
// Counter.js
import React, { useState } from 'react';
const Counter = ({ initialCount }) => {
const [count, setCount] = useState(initialCount);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
// Counter.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import Counter from './Counter';
test('renders with initial count', () => {
render(<Counter initialCount={5} />);
expect(screen.getByText('Count: 5')).toBeInTheDocument();
});
2. Testing User Interaction
Consider a component Button.js
:
//button.js
import React from 'react';
const Button = ({ onClick, label }) => (
<button onClick={onClick}>{label}</button>
);
export default Button;
//test_button.js
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import Button from './Button';
test('Button has correct label and responds to click event', () => {
const handleClick = jest.fn();
const { getByText } = render(<Button onClick={handleClick} label="Click me" />);
fireEvent.click(getByText('Click me'));
expect(getByText('Click me')).toBeInTheDocument();
expect(handleClick).toHaveBeenCalledTimes(1);
});
In this test, we render the Button component with the text “Click me”, simulate a click event, and verify that the button was clicked exactly once and the text “Click me” is in the document.
3. Testing Conditional Rendering
// ConditionalGreeting.js
import React from 'react';
const ConditionalGreeting = ({ isLoggedIn }) => (
isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>
);
export default ConditionalGreeting;
// ConditionalGreeting.test.js
import { render, screen } from '@testing-library/react';
import ConditionalGreeting from './ConditionalGreeting';
test('renders welcome back when logged in', () => {
render(<ConditionalGreeting isLoggedIn={true} />);
expect(screen.getByText('Welcome back!# I'll search for a couple more examples to complete the request.
search("React Testing Library examples")
4. Testing Class Changes
You can also test how your component behaves when it receives different kinds of user interaction. In this example, we’re testing that a Link
component changes its class when it’s hovered over:
// Link.js
import { useState } from 'react';
const STATUS = {
HOVERED: 'hovered',
NORMAL: 'normal',
};
export default function Link({ page, children }) {
const [status, setStatus] = useState(STATUS.NORMAL);
const onMouseEnter = () => {
setStatus(STATUS.HOVERED);
};
const onMouseLeave = () => {
setStatus(STATUS.NORMAL);
};
return (
<a
className={status}
href={page || '#'}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
{children}
</a>
);
}
// Link.test.js
import renderer from 'react-test-renderer';
import Link from '../Link';
it('changes the class when hovered', () => {
const component = renderer.create(
<Link page="http://www.facebook.com">Facebook</Link>,
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
The test asserts that the initial rendering matches a saved snapshot. The snapshot will contain the output of the Link
component given the props specified in the test.
5. Testing Checkbox Interaction
In this example, we’re testing a CheckboxWithLabel
component that changes its label when it’s clicked:
// CheckboxWithLabel.js
import { useState } from 'react';
export default function CheckboxWithLabel({ labelOn, labelOff }) {
const [isChecked, setIsChecked] = useState(false);
const onChange = () => {
setIsChecked(!isChecked);
};
return (
<label>
<input type="checkbox" checked={isChecked} onChange={onChange} />
{isChecked ? labelOn : labelOff}
</label>
);
}
// CheckboxWithLabel.test.js
import { cleanup, fireEvent, render } from '@testing-library/react';
import CheckboxWithLabel from '../CheckboxWithLabel';
// Note: running cleanup afterEach is done automatically for you in @testing-library/[email protected] or higher
// unmount and cleanup DOM after the test is finished.
afterEach(cleanup);
it('CheckboxWithLabel changes the text after click', () => {
const { queryByLabelText, getByLabelText } = render(
<CheckboxWithLabel labelOn="On" labelOff="Off" />,
);
expect(queryByLabelText(/off/i)).toBeTruthy();
fireEvent.click(getByLabelText(/off/i));
expect(queryByLabelText(/on/i)).toBeTruthy();
});
This test first checks that the “Off” label is displayed, then simulates a click on the checkbox and checks that the “On” label is displayed.
The test can also be written using Enzyme:
// CheckboxWithLabel.test.js
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import CheckboxWithLabel from '../CheckboxWithLabel';
Enzyme.configure({ adapter: new Adapter() });
it('CheckboxWithLabel changes the text after click', () => {
// Render a checkbox with label in the document
const checkbox = shallow(<CheckboxWithLabel labelOn="On" labelOff="Off" />);
expect(checkbox.text()).toBe('Off');
checkbox.find('input').simulate('change');
expect(checkbox.text()).toBe('On');
});
Conclusion
These examples should give you a good starting point for testing React components. As you can see, Jest and the React Testing Library provide powerful tools for simulating user interaction, testing component output, and ensuring that your components continue to work as expected as your application evolves.
Clear lessons, easy to follow even for a beginner. Very knowledgeable and gives great encouragement to beginner coders. Really helpful and responded to questions quickly. No problem too big or too small. Friendly teaching style meant I didn’t feel embarrassed to ask silly questions.
Louise
I liked Anuj’s style of teaching, really clear and easy to understand!
Carolina Opazo
The style of the learning structure has been very constructive and the availabilityof the instructor helps to build confidence and security to try, fail and learn. 5 stars to the instructor style!
Maryl Duprat
Anuj was a fantastic instructor, super informative and knowledgeable. He was very approachable with questions, and clear and concise in his explanations. 🙂
Alice Pinch
Anuj is a great instructor who is very knowledgeable and passionate about what he teaches. He worked well with his co-instructor, which led to a positive learning experience. The course itself is an introductory course but still has a lot of material to cover, but Anuj was very meticulous in explaining concepts to ensure lessons were executed and understood. He is a great listener and always willing to answer questions no matter how obvious (and sometimes silly). I have already signed up for another course and am hoping he will be part of the team!
Pam
Well-structured lessons with the use of diagrams/images to help students understand concepts. Demonstrated examples step-by-step and answered any queries students had.
Maria
Anuj is a great instructor, who was incredibly dedicated to the course, both during teaching hours and after them. I really enjoyed the fun material he posted after the sessions, such as games and fun facts on our Slack channel. If I were to give a piece of constructive advice, I would recommend slowing down a little bit with the course material. For us newbies it can sometimes be difficult to keep up. That being said, I highly appreciate that he was always responsive and patient with any queries or questions that I had, and so any confusions were very temporary. Slowing the pace down a bit would be the cherry on top!
Raimunda Bukartaite
Really engaging and helpful, always happy to answer any questions I had!
Muskaan
Overall very good and in depth teaching. Sometimes more explanation would be better, maybe slow down when showing examples.
Dominika
I really liked that the classes involved solving problems during the class and it wasn’t a person speaking alone all the time. I really appreciated the support and commitment of the instructors during the whole course.
Victoria Caballero
I thought the instructions were really clear and the instructor was very encouraging. They were always open to answering questions and very patient with the class. I think the lesson would have benefitted from more “teacher persona” tactics to get the class more involved with their cameras on and answering questions so that the lesson would have a more interactive feel.
Rashida Adekunle
Clear instructions and useful coding habits highlighted.
Asnath Lubanza
Always very helpful – going an extra mile to aid students. Always welcomes questions and will not make you feel bad or stupid for asking.
Maria
First, Anuj makes efforts to simplify explanations of a concept and gives practical examples in a structured way. Second, he doesn’t just teach us things. He takes time to listen to our concerns and motivates us by sharing his personal experience and thoughts as an experienced software engineer.
Amanda Kartikasari
Patient when teaching, explains everything clearly and simply for non-techies(!), willing to go slower if us students find it fast or hard to keep up or understand, willing to go over topics and ensure everyone understands. Anuj goes above and beyond for the students despite understanding and learning differences. Outside of class and after class – a passionate and great teacher.
Ameera
Really enjoyed coding alongside you, clear and concise instructions and even some bits that were necessarily on the slides, but were SUPER helpful to us and our understanding of the language
Francessca
Very informative, supportive and friendly. The latter made you very approachable so I felt more at ease asking for help with things.
Amy Mulligan
I found the usecases made things very easy to follow and understand – when I was learning by myself, I was confused at some of the concepts because I couldn’t see how they would be applied, whereas you gave real-life examples that really helped it slot together!
Anastasija Medvedeva
confident and helpful
louise
Anuj was a clear and concise instructor, who was always happy to help no matter the timing of it. I also liked that he made everyone feel welcome and fostered an inclusive culture, which made our team not afraid to present even if we were slightly unsure if our project work would live up the the standard of the rest of the group.
Deni Hancox
Very supportive, very clear and gives great demonstrations and examples. The extra slides and YouTube videos were also a huge help for me.
Daisy Dobson
Very thorough in terms of showing how to get the code to initially work and what the different errors could be, as well as how to fix them. Very efficient teaching style!
Cerys Cullen
I liked that you walked through what you were writing for the code and showed different expamples for the same concept
Fabiha Chowdhury
Used relevant examples of code in the real world, and took the time to explain difficult ideas.
Chloe
I like you are very helpful and teaching the things again and again and make people comfortable to ask you a questions.
Pinar Seker
I think you taught everything really well, thank you! All questions you answered concisely and shared lots of resources.
Ria Kakkad
Your words were organize, not chaotic. You know how to pass the knowledge to students. Thank you
JL
Very clear speaker. Passionate about what you are speaking about. Add your own knowledge into the classes and don’t just read from the script/slides. Explain things in an easy to understand manner. Always available to help.
Caroline Bell
Great teacher, extremely helpful and taught the course in a way which was understandable
Emma McKinney
I liked it, it was very helpful with the tips and notes, also the knowledge was definitely evident so was trustworthy and made me feel comfortable when I thought I asked a stupid question and always had help available.
Sermin Efendi
Well researched resources. Easy explanation. Great examples.
Sefat
Really clear, concise and supportive. Broke down complicated problems easily with other examples. The extra content you created with your slides were incredibly helpful.
Nalani St Louis
lots of personality and availability to answer questions/doubts
Liyaan Khoso
Everything Anuj! As a teacher myself, I loved learning from you. You were so patient with us and answered every question we asked so well. You also had away of making difficult things seem easy. Your passion and dedication showed.
Onyeoma Adigwe
The presentations you prepare yourself are much more information dense, available and I found some topics are much easier to grasp using them, so grateful for the extra materials you always provide.
Asya Seagrave
very structured and easy to follow. Very supportive with all the students and always giving insightful advices.
Miriem Shaimi
I really like how you try to simplify and give real-life analogies to coding concepts. Really grateful for all the support you give to us students, especially by addressing our questions and for being available when we are lost. Really grateful for it as it shows how much you care for your students.