Testing Lab 1: Your First Component Test
Objectives
- Install React Testing Library
- Create Your First Component Test
Steps
This lab is designed to start with the code after finishing:
Lab 25: Redux with React
In these testing labs, Create React App was used to create the React application. Create React App is no longer actively maintained but it is an easy way to create a React application that is already setup to do testing with Jest and React Testing Library. The rest of this course has been updated to use the maintained and modern Vite project to create your react application but I continue to include this section because their are millions of applications that are still being maintained that were created using Create React App and use Jest as the JavaScript testing library.
Install React Testing Library
Make a new directory in your code directory
testing
.In that directory, download or clone the following branch to start testing.
git clone https://github.com/craigmckeachie/keeptrack-js.git keeptrack
cd keeptrack
git checkout lab25OR
Visit this link and click
Code > Download
Open a
command prompt
(Windows) orterminal
(Mac).Change the current directory to
code\testing\keeptrack
.Run one of the following commands to install the project dependencies:
npm
npm install
Yarn
yarn install
Run one of the following commands to run the tests:
npm
npm test
Yarn
yarn test
Press
a
to run all tests.Verify the test created by Create React App fails.
FAIL src/App.test.js
Unable to find an element with the text: /learn react/i.Open the
keeptrack
directory in the editor of your choice and then open the filesrc/App.test.js
Update the test code.
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
- test('renders learn react link', () => {
- const { getByText } = render(<App />);
- const linkElement = getByText(/learn react/i);
- expect(linkElement).toBeInTheDocument();
-});
+ test('should render without crashing', () => {
+ render(<App />);
+ });Note: We will test the the content (as the generated test was) in a HomePage component test in the next step.
Verify the test now passes.
PASS src/App.test.js
Create Your First Component Test
Create the file
src\home\HomePage.test.js
.Add a test to verify the component shallow renders without crashing.
src\home\HomePage.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import HomePage from './HomePage';
test('renders home heading', () => {
render(<HomePage />);
expect(screen.getByRole('heading')).toHaveTextContent('Home');
});Verify the test passes.
PASS src/home/HomePage.test.js