it-source

리액트 테스트 라이브러리를 사용하여 요소 내부에 텍스트 확인

criticalcode 2023. 2. 22. 22:17
반응형

리액트 테스트 라이브러리를 사용하여 요소 내부에 텍스트 확인

Testing Library를 사용하여 리액트 앱에 대한 테스트를 작성하고 있습니다.텍스트가 표시되는지 확인하고 싶지만 이미 다른 곳에 표시되어 있기 때문에 특정 장소에 표시되어 있는지 확인해야 합니다.

쿼리 테스트 라이브러리 문서에는getByText쿼리는container이 매개 변수를 사용하면 컨테이너 내에서 검색할 수 있을 것 같습니다.이렇게 하려고 했는데container그리고.text파라미터는 documents에서 지정된 순서로 지정합니다.

const container = getByTestId('my-test-id');
expect(getByText(container, 'some text')).toBeTruthy();

에러가 표시됩니다.matcher.test is not a function.

파라메스를 반대로 하면:

const container = getByTestId('my-test-id');
expect(getByText('some text', container)).toBeTruthy();

다른 에러가 표시된다.Found multiple elements with the text: some text

즉, 지정된 컨테이너 내부를 수색하고 있지 않습니다.

어떻게 하는지 이해가 안 가는 것 같아요.getByText내가 뭘 잘못하고 있는 거지?

다음과 같은 용도로 사용하는 것이 좋습니다.

render(<MyComponent />)
const { getByText } = within(screen.getByTestId('my-test-id'))
expect(getByText('some text')).toBeInTheDocument()

또 다른 방법

import {render, screen} from '@testing-library/react';

...

  render(<MyComponent />);
  expect(screen.getByTestId('my-test-id')).toHaveTextContent('some text');

이 시점에서 이 기능을 사용하는 것이 권장됩니다.screen렌더링 결과 대신.

(StackOverflow는 이유를 설명하는 KC Dobbs 문서에 포인트를 게시합니다.react-testing-library - Screen vs Render 쿼리)

이렇게 하면 특정 항목에 초점을 맞추어 보다 정확하게 지정할 수 있습니다.

expect(queryByTestId("helperText")?.textContent).toContain("Help me!");

언급URL : https://stackoverflow.com/questions/58976251/checking-text-appears-inside-an-element-using-react-testing-library

반응형