0
0

More than 1 year has passed since last update.

Jest React TypeScript toBeChecked()を使ってボタンとチェックボックスの状態をテストする

Last updated at Posted at 2022-12-12

概要

jestでボタンとチェックボックスの初期状態を確認します。

開発環境

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>
		<input type ="checkbox" />
	</div>
  );
}

export default App;

テストコード

App.text.tsx

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

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

	expect(colorButton).toBeEnabled();

	const checkbox = screen.getByRole('checkbox');
	expect(checkbox).not.toBeChecked();


})


実際の動き

下gifアニメは、テストコード確認してるときの様子です。
プロダクトコードのcheckboxの値を変えてPassとFailを確認しています。
ウィンドウの並びは左から順に、テストコード、プロダクトコード、プレビューという構成です。

checkbox_enabledpart2.gif

github

参考

Section2 18 19

toBeEnabled()

checkbox

image.png

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