반응형
React Testing Library
React Testing Library (이하 RTL)은 구현 기반의 테스트 도구인 Enzyme의 대안으로 자리 잡은 테스트 도구다. RTL은 사용자 관점에서 테스트를 하는 반면에, Enzyme은 상태 값, 상태 변수에 대해 테스트를 한다는 차이가 있다. React 테스트 도구는 RTL과 Enzyme 외에도 여러 가지가 있다.
- react-testing-library: 가벼운 React DOM 테스트 유틸
- Enzyme: Airbnb가 만든 React를 위한 JavaScript 테스트 유틸
- Jest: JavaScript 테스트 프레임워크(React 포함)
- React-unit: React를 위한 가벼운 단위테스트 라이브러리
- Skin-deep: 얕은 렌더링을 지원하는 React 테스트 유틸
- Unexpected-react: React 컴포넌트와 이벤트를 발생시켜주는 플러그인
사용법
설치
npm install --save-dev @testing-library/react
테스트 할 컴포넌트
// hidden-message.js
import * as React from 'react'
// NOTE: React Testing Library works well with React Hooks and classes.
// Your tests will be the same regardless of how you write your components.
function HiddenMessage({children}) {
const [showMessage, setShowMessage] = React.useState(false)
return (
<div>
<label htmlFor="toggle">Show Message</label>
<input
id="toggle"
type="checkbox"
onChange={e => setShowMessage(e.target.checked)}
checked={showMessage}
/>
{showMessage ? children : null}
</div>
)
}
export default HiddenMessage
테스팅 코드 작성
// __tests__/hidden-message.js
// these imports are something you'd normally configure Jest to import for you
// automatically. Learn more in the setup docs: https://testing-library.com/docs/react-testing-library/setup#cleanup
import '@testing-library/jest-dom'
// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required
import * as React from 'react'
import {render, fireEvent, screen} from '@testing-library/react'
import HiddenMessage from '../hidden-message'
test('shows the children when the checkbox is checked', () => {
const testMessage = 'Test Message'
render(<HiddenMessage>{testMessage}</HiddenMessage>)
// query* functions will return the element or null if it cannot be found
// get* functions will return the element or throw an error if it cannot be found
expect(screen.queryByText(testMessage)).toBeNull()
// the queries can accept a regex to make your selectors more resilient to content tweaks and changes.
fireEvent.click(screen.getByLabelText(/show/i))
// .toBeInTheDocument() is an assertion that comes from jest-dom
// otherwise you could use .toBeDefined()
expect(screen.getByText(testMessage)).toBeInTheDocument()
})
공식 문서
https://testing-library.com/docs/react-testing-library/intro/
React Testing Library | Testing Library
React Testing Library builds on top of DOM Testing Library by adding
testing-library.com
반응형
'웹_프론트엔드 > 로드맵 챌린지' 카테고리의 다른 글
테스트 프레임워크 - Enzyme (0) | 2022.03.16 |
---|---|
테스트 프레임워크 - Cypress (0) | 2022.03.15 |
테스트 프레임워크 - Jest (0) | 2022.03.11 |
CSS 프레임워크 - Bulma (0) | 2022.03.10 |
CSS 프레임워크 - Materialize CSS (0) | 2022.03.08 |