React Testing Library로 List 요소 찾기

artit·2021년 9월 28일
1

React Testing Library

목록 보기
1/1

리액트로 웹사이트를 개발하던중, map()함수를 이용해서 동적인 목록을 만들게 되었는데요.

<img url="큰 이미지로 보이는 화면"/>
<ul>
    <li>미리보기 이미지1</li>
    <li>미리보기 이미지2</li>
    <li>미리보기 이미지3</li>
</ul>    

li 요소를 클릭하는 테스트 코드를 작성하고 싶은데,
li 요소는 react-test-library로 어떻게 찾아야 될까요?

예제 1: 동적인 목록요소를 포함한 컴포넌트

const fruits = ["Bananas", "Apples", "Strawberries", "Grapes", "Oranges"]

function FruitList() {
  return (
    <section>
      <h1 id="fruits-heading">Fruits</h1>
      <ul aria-labelledby="fruits-heading">
        {fruits.map(fruit => (
          <li key={fruit}>{fruit}</li>
        ))}
      </ul>
    </section>
  )
}

fruits라는 과일이름이 들어있는 array가 있고,
FruitList()함수는 과일목록을 포함한 컴포넌트를 리턴해주고 있어요.

예제 2: 목록의 아이템 갯수를 확인하는 테스트 코드

import React from "react"
import { render, screen, within } from "@testing-library/react"

it("should render list of 5 fruits", () => {
  render(<FruitList />)
  const list = screen.getByRole("list", {
    name: /fruits/i,
  })
  const { getAllByRole } = within(list)
  const items = getAllByRole("listitem")
  expect(items.length).toBe(5)
})

이름이 fruits인 list를 찾고, 그 안에서 listitem을 getAllByRole로 찾을 수 있었습니다.

이미 부여된 role을 갖고있는 요소목록은 list of roles을 참고하세요.

더 볼거리

아래 포스트를 통해 방법을 알게 되었는데, 일부를 옮겨왔습니다.
Role에 대해서 더 깊이 있는 내용은 아래 포스트를 참고해 주세요.
[Testing Lists Items With React Testing Library]

testing library 공식 홈페이지 about queries

  • 더 공부할 것
    const list = screen.getByRole("list", {
        name: /fruits/i,
      })
	list를 찾을 때, 매개변수로 넘기는 오브젝트{} 속 name option 사용법 이해하기. 
	(혹시 잘 알고 계신분 있다면 알려주세요!)
profile
좌충우돌 개발 일기

0개의 댓글