Async Methods[Testing Library]

SnowCat·2023년 3월 8일
0

Testing Library

목록 보기
9/11
post-thumbnail

findBy 쿼리

const button = screen.getByRole('button', {name: 'Click Me'})
fireEvent.click(button)
await screen.findByText('Clicked once')
fireEvent.click(button)
await screen.findByText('Clicked twice')
  • getBy 쿼리와 waitFor 메서드를 겨랍한 형태
  • 엘리먼트가 나오지만 즉시 변화되지 않는 경우에 활용 가능

waitFor

function waitFor<T>(
  callback: () => T | Promise<T>,
  options?: {
    container?: HTMLElement
    timeout?: number //1000ms
    interval?: number //50ms
    onTimeout?: (error: Error) => Error // 타임아웃시 오류 출력
    mutationObserverOptions?: MutationObserverInit // 값 변경시 콜백 다시실행
  },
): Promise<T>
  • 일정 시간동안 기다리게 하고자 하는 경우 waitFor 메서드 호출 가능
  • 동기 함수의 경우 조건이 만족될 때 까지 interval 간격마다 함수를 재호출하게 됨
  • 프로미스를 반환하는 함수의 경우 콜백에서 오류가 발생할 때 함수를 재호출하게 됨
    이 경우 false값을 반환하는 것으로는 즉시 재호출이 되지 않음에 유의

waitForElementToBeRemoved

function waitForElementToBeRemoved<T>(
  callback: (() => T) | T,
  options?: {
    container?: HTMLElement
    timeout?: number
    interval?: number
    onTimeout?: (error: Error) => Error
    mutationObserverOptions?: MutationObserverInit
  },
): Promise<void>
  
// 실제 예시
const el = document.querySelector('div.getOuttaHere')

waitForElementToBeRemoved(document.querySelector('div.getOuttaHere')).then(() =>
  console.log('Element no longer in DOM'),
)
el.setAttribute('data-neat', true)
el.parentElement.removeChild(el)
  • DOM이 사라지는 것을 확인하기 위해서는 waitForElementToBeRemoved 메서드를 사용

DOM이 없는 경우를 체크하는 방법

// 1. queryBy 메서드를 사용해 toBeNull 체크
const submitButton = screen.queryByText('submit')
expect(submitButton).toBeNull()

// 2. 여러개가 들어오는 경우 queryAllBy 메서드를 사용해 길이 확인
const submitButtons = screen.queryAllByText('submit')
expect(submitButtons).toHaveLength(0) // expect no elements

// 3. not.toBeInTheDocument 사용
import '@testing-library/jest-dom'
const submitButton = screen.queryByText('submit')
expect(submitButton).not.toBeInTheDocument()

출처:
https://testing-library.com/docs/dom-testing-library/api-async

profile
냐아아아아아아아아앙

0개의 댓글