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

Test

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) {
    super(props)

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


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

    </Router>
  );
}

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', () => {
  render(<App/>);
  const linkElements = screen.getAllByRole("link");
  userEvent.click(linkElements[0])
  const NewTitleElement = screen.getByText("New Title");
  expect(NewTitleElement).toBeInTheDocument();
});

Run test

npm run test

Add a Comment

發佈留言必須填寫的電子郵件地址不會公開。