React+Test => Startup

Strengthen your system! Coding the main flow isn’t the only task your need to complete when you try to build a new system. Creating tests for your system will make you feel confident about the project, especially each time you want to push commits.

This time we will build a test for a react component using testing-library, including clicking the element of the component and checking it change.

Create React Project

npx create-react-app <app-name> --template typescript 

Install React

cd <app-name>
npm i react react-router-dom sass react-test-rederer
npm i typescript @types/node @types/react @types/react-dom @types/jest @types/react-router-dom
npm i jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer

quick start

npm run start


Update App.tsx

import React from 'react';
import logo from './logo.svg';
import './App.css';
import {HashRouter as Router, Route, Link, Routes} from 'react-router-dom';

const home = <p>Home Page</p>
type TitleSchema = {
  VersionTag: string
export class Title extends React.Component<TitleSchema, any> {

  constructor(props: TitleSchema) {

  render() {
    return <p>{this.props.VersionTag}</p>

function App() {
  return (
      <Link to="/title">title</Link><br/>
        <Route path="/" element={home}/>
        <Route path="/title" element={<Title VersionTag="New Title"/>}/>


export default App;

Update App.test.tsx

import React from 'react';
import { render, screen } from '@testing-library/react';
import  userEvent  from '@testing-library/user-event';
import App from './App';

test('renders learn react link', () => {
  const linkElements = screen.getAllByRole("link");[0])
  const NewTitleElement = screen.getByText("New Title");

Run test

npm run test

Add a Comment