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
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-ts.git keeptrackcd keeptrackgit checkout testing-start- OR - Visit this link and click - Code > Download
- Open a - command prompt(Windows) or- terminal(Mac).
- Change the current directory to - code\testing\keeptrack.
- Run one of the following commands to install the project dependenciess: - npmnpm install- Yarnyarn install
- Run one of the following commands to run the tests: - npmnpm test- Yarnyarn test
- Press - ato run all tests.
- Verify the test created by Create React App fails. FAIL src/App.test.tsxUnable to find an element with the text: /learn react/i.
- Open the - keeptrackdirectory in the editor of your choice and then 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 Your First Component Test
- Create the file - src\home\HomePage.test.tsx.
- Add a test to verify the component shallow renders without crashing. - src\home\HomePage.test.tsximport 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.tsx