- Published on
[React Testing] Hooks 테스팅
- Authors

jangth
리액트 훅은 리액트 렌더링 메커니즘을 따른 함수로 독립적으로 로직을 갖고 있다. 따라서 단위 테스트 대상으로 적합하다.
리액트 훅을 실행하고 테스트하려면 리액트 컴포넌트가 필수다. 때문에 RTL에서는 renderHook API를 제공해주는데, 리액트 컴포넌트 없이도 훅을 실행할 수 있도록 도와준다.
useModal 테스트 예시
import { act, renderHook } from '@testing-library/react'
import { useModal } from '../useModal'
it('초기 모달의 상태는 false이다.', () => {
const { result } = renderHook(useModal)
expect(result.current.isVisible).toBe(false)
})
it('show()를 호출하게 되면 isVisible은 true가된다.', () => {
const { result } = renderHook(useModal)
act(() => {
result.current.show()
})
expect(result.current.isVisible).toBe(true)
})
it('hide()를 호출하게 되면 isVisible은 false가된다.', () => {
const { result } = renderHook(useModal)
act(() => {
result.current.hide()
})
expect(result.current.isVisible).toBe(false)
})
it('toggle()를 호출하게 되면 isVisible은 기존 상태와 반대의 boolean값이 된다.', () => {
const { result } = renderHook(useModal)
act(() => {
result.current.toggle()
})
expect(result.current.isVisible).toBe(true)
})
- renderHook은 result와 renderer를 반환한다. ﹒ result : 훅을 호출하여 얻은 결과를 current객체에 저장하여 반환 (result.current.반환 값) ﹒ renderer : 훅을 원하는 인자와 함께 새로 호출하여 상태를 갱신한다. (주로 Props 변경에 따른 컴포넌트 상태를 검증할 때 사용)
- act ﹒ 상호작용(렌더링, 이펙트 등)을 함께 그릅화하고 실행해 렌더링과 업데이트가 실제 앱이 동작하는 것과 유사한 방식으로 동작한다. 따라서 테스트 환경에서 컴포넌트 렌더링, 업데이트 결과를 jsDOM에 반영할 때 사용한다.
✅ render함수와 유저이벤트(@testing-library/user-event)는 내부적으로 act 함수를 호출하여 상태를 반영한다.
