- Install React Testing Library
- Create Your First Component Test
This lab is designed to start with the code after finishing:
Lab 25: Redux with React
-
Open a
command prompt
(Windows) orterminal
(Mac). -
Change the current directory to
code\keeptrack
. -
You probably DON'T need to DO the steps below but they are listed for completeness.
If you recently created your React project using Create React App then the following steps to install React Testing Library will have been done for you when the project was created.
-
Run one of the following sets of commands:
npm install --save @testing-library/react @testing-library/jest-dom
yarn add @testing-library/react @testing-library/jest-dom
-
Create the file
src\setupTests.ts
-
Add the following code to configure enzyme.
// react-testing-library renders your components to document.body, // this adds jest-dom's custom assertions import '@testing-library/jest-dom/extend-expect';
-
-
Run one of the following commands to run the tests:
npm test
yarn test
-
Press
a
to run all tests. -
Verify the test created by Create React App fails.
FAIL src/App.test.tsx Unable to find an element with the text: /learn react/i.
-
Open the file
src/App.test.tsx
-
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.tsx
-
Create the file
src\home\HomePage.test.tsx
. -
Add a test to verify the component shallow renders without crashing.
import React from 'react'; import { render, screen } from '@testing-library/react'; import App from './App'; test('renders home heading', () => { render(<App />); expect(screen.getByRole('heading')).toHaveTextContent('Home'); });
-
Verify the test passes.
PASS src/home/HomePage.test.tsx
-
Add a test to verify the component renders a title tag.
// ... test('renders title tag', () => { let wrapper: ShallowWrapper; wrapper = shallow(<HomePage />); expect(wrapper.exists('h2')).toBeTruthy(); });
-
Verify the test passes.
PASS src/home/HomePage.test.tsx
-
Add a test to verify the component renders a title.
// ... test('renders title', () => { let wrapper: ShallowWrapper; wrapper = shallow(<HomePage />); expect(wrapper.find('h2').text()).toBe('Home'); });
-
Verify the test passes.
PASS src/home/HomePage.test.tsx