Basic Test
- Test interactivity using fireEvent
- Jest-dom assertions
: toBeEnabled()
: toBeDisabled()
: toBeChecked()
- getByRole option { name : }
- Jest describe to group tests
테스팅 라이브러리를 위한 ESLint와 Prettier 설정
ESLint
- ESLint는 JavaScript에서 흔히 사용되는 Linter이다.
- Linter : 정적 텍스트(static text)를 분석하고 linter 규칙을 위반하는 구문을 마킹하는 도구이다.
- static : 코드가 작성된 그대로의 '정적'인 코드 분석을 한다. (코드가 어떻게 '실행되는지'에 대해서는 분석을 하지 않음)
- Linting은 코드의 스타일을 일관적으로 유지하는 데에 유용한다.
- 여러 엔지니어가 프로젝트를 작업 중일 때 특히 유용한다.
- 코드의 오류를 잡아낼 수 있다.
jest-dom을 위한 ESLint plugin
npm install eslint-plugin-testing-library eslint-plugins-jest-dom
packages.json에서 eslintConfig를 삭제해주고 따로 .eslintrc.json 파일을 생성해준다.
plugins : 사용하고자 하는 플러그인
extends : 해당 플러그인에 대한 특정한 규칙
Prettier
- Prettier는 Formatter로 코드를 자동으로 Formatting 해준다.
- 들여쓰기와 빈칸에만 제한이 되어 있다.
- Linters는 확장된 formatter에 가깝다. 형식도 수정과 함게 스타일도 수정해 준다.
vscode에서 사용시 lint와 prettier 설정
루트폴더에서 .vscode폴더 / setting.json
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.alwaysShowStatus": true,
"editor.formatOnSave": true
}
버튼색 변경 테스트
function App() {
return (
<div>
<button style={{ backgroundColor: "red" }}>Change to blue</button>
</div>
);
}
export default App;
ex1) 역할로 button을 찾고, 배경이 red인지 확인하는 테스트
test("버튼색 변경된다!", () => {
render(<App />);
//버튼 역할의 이름이 change to blue인 element를 찾아라
const colorButton = screen.getByRole("button", { name: "Change to blue" });
//그 버튼은 배경색이 red이기를 기대해!
expect(colorButton).toHaveStyle({ backgroundColor: "red" });
});
만약, 해당 역할을 잘못 입력했거나, 존재하지 않는 역할을 넣었을 때
testing library로부터 해당 역할로는 access가능한 요소를 찾을 수 없다는 경고가 발생하므로
필요할 경우 어떤 역할이 있는지 알아볼때 유용하게 사용할 수 있다.
ex2) 버튼 클릭 시 빨강에서 파랑으로 변경되는 이벤트 테스트
checkBox - Button disabled
checkBox를 누르면 button이 활성화, 체크해제하면 button이 비활성화되는 코드에대한 테스트 코드 작성
testing library의 fireEvent 페이지
fireEvent보다 userEvent가 실제 user들이 interaction하는 방식에 더욱 근접하게 작동한다.
자세한 내용 > https://ph-fritsche.github.io/blog/post/why-userevent
npm install @testing-library/user-event @testing-library/dom
fireEvent > userEvent로 변경
'Archive' 카테고리의 다른 글
[Git] Merge - fast Forward merge, commit merge (merge 방식) (0) | 2022.10.26 |
---|---|
[Git] Git 사용 기초 ( local-remote / branch-head / push-pull ) (0) | 2022.10.26 |
[React] Recoil 상태관리 라이브러리 기초 (0) | 2022.09.11 |
[RN] react-native-video (evaluating 'RCTVideolastance.Constants' error) (0) | 2022.08.27 |
[React] TDD in reactjs with RTL and Jest - (1) 기초 이론 (0) | 2022.08.08 |