0
0

More than 1 year has passed since last update.

Jest React TypeScript ボタンの色をテストコードで評価する

Last updated at Posted at 2022-12-07

概要

の続きです。
ボタンの色を検証するテストコードを実装します。

開発環境

IDE:GitHub CodeSpaces
OS:windows10
言語:TypeScript

├── @testing-library/jest-dom@5.16.5
├── @testing-library/react@13.4.0
├── @testing-library/user-event@13.5.0
├── @types/jest@29.2.3
├── @types/node@16.18.4
├── @types/react-dom@18.0.9
├── @types/react@18.0.25
├── jest@29.3.1
├── react-dom@18.2.0
├── react-scripts@5.0.1
├── react@18.2.0
├── UNMET DEPENDENCY test@jest
├── ts-jest@29.0.3
├── typescript@4.9.3
└── web-vitals@2.1.4

手順

プロダクトコード

押せないボタンです。

App.tsx
import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div >
    <button style={{backgroundColor: 'red'}}>Change to blue</button>
    </div>
  );
}

export default App;

テストコード

App.test.tsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';

test('button has correct initial color', () => {
   const { container } = render(<App />);

    // find an element with a role of button and text of 'Change to blue'
   const colorButton = screen.getByRole('button',{ name:'Change to blue' });

   // ボタンの初期色が赤色であることを確認
    expect(colorButton).toHaveStyle({backgroundColor: 'red'})
});

test('button turns blue when clicked', () => {});

画面の状態

左側がCodeSpacesの画面、右側がReactのアプリです。
テストコードをred→yellow→redとすると、Pass,Fail,Passとなるので機能しています。
下gifアニメはその時の様子です。

RedToYelloToRed.gif

githubの差分

参考

udemy
Section2.13

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0