LoginSignup
0
0

More than 1 year has passed since last update.

jest react typescript チェックボックスのラベルを探す

Last updated at Posted at 2022-12-14

概要

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';
	const [disabled,setDisabled] = useState(false);
	const [disabledSecond,setDisabledSecond] = useState(true);
  return (
    <div >
    <button 
		style={{backgroundColor: buttonColor}} 
		onClick={() => setButtonColor(newButtonColor)}
		disabled={disabled}
		>
		Change to {newButtonColor}
	</button>
		{/* <input type ="checkbox"  checked={true}/> */}
		<input 
			type ="checkbox"
			id="disable-button-checkbox"
			defaultChecked = {disabled}
			onChange={(e) => setDisabled(e.target.checked)} 
			/>
			<label htmlFor="disable-button-checkbox">Disable button</label>
		
			<input 
			type ="checkbox"
			id="disable-button-checkbox-two"
			defaultChecked = {disabledSecond}
			onChange={(e) => setDisabledSecond(e.target.checked)} 
			/>
			<label htmlFor="disable-button-checkbox-two">Disable button</label>
		</div>

  );
}

export default App;


テストコード

App.test.tsx

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

test('Checkbox disable button on first click and enables on second click',()=>{
	render(<App />);
	// 使うタイミング 複数チェックボックスがあるときに使えそう
	const checkbox = screen.getAllByRole('checkbox',{name: 'Disable button'});

	const colorbutton = screen.getByRole('button',{name: 'Change to blue'});

	fireEvent.click(checkbox[0]);
	expect(colorbutton).toBeDisabled();

	fireEvent.click(checkbox[0]);
	expect(colorbutton).toBeEnabled();
});

動かしたときの様子

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

TestLabel1.gif

github

参考

section 23

htmlforについて初見だったんで調べました。
Reactはhtmlとjavascriptが一つのファイルになっているから、javascript側とhtml側のforが被ってしまった。
その被りを解消するためにhtml側のforをhtmlforにしたようです。

image.png

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