LoginSignup
0
0

More than 1 year has passed since last update.

Jest React TypeScript でボタン押下の挙動をテストする

Last updated at Posted at 2022-12-13

概要

jest でボタンを押したときの動作をテストします。

テストする対象

ボタンはクリックされると赤色から青色に変化します。
色の変化とボタン上の文字をテストします。
chapter15product.gif

開発環境

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 {useState} from 'react';
import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
	const [buttonColor, setButtonColor] = useState('red');
	const newButtonColor = buttonColor === 'red'? 'blue' : 'red';

  return (
    <div >
    <button 
		style={{backgroundColor: buttonColor}} 
		onClick={() => setButtonColor(newButtonColor)}>
		Change to {newButtonColor}
		</button>
	</div>
  );
}

export default App;


テストコード

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


test('button has correct initial color', () => {
	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'})

	// ボタンを押す
	fireEvent.click(colorButton);

	// クリック後ボタンは青色になる
	expect(colorButton).toHaveStyle({ backgroundColor:'blue'});

	// クリック後ボタンのテキストは「Change to red」になる。
	expect(colorButton).toHaveTextContent('Change to red');
	
	// ボタンを押す
	fireEvent.click(colorButton);

	// クリック後ボタンは赤色になる
	expect(colorButton).toHaveStyle({ backgroundColor:'red'});

	// クリック後ボタンのテキストは「Change to blue」になる。
	expect(colorButton).toHaveTextContent('Change to blue');


});

test('button turns blue when clicked', () => {
	render(<App />);
	const colorButton = screen.getByRole('button',{ name:'Change to blue'});



});

実行時の様子

下のアニメはテストを実行時の様子です。
最初にAllGreenの場合を確認して ボタンの初期色を青に変えてFailにしています。

chapter15productTestPattern.gif

感想

jest-domのドキュメントが良いです。
プロダクトコードとテストコードが載っており、使い方をイメージしやすいです。

参考

toHaveTextContent

udemy
section2 15 16

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