mercredi 25 novembre 2020

What is the difference "getByText" and "getByTestId" ? In testing-library/react

I have a question.

  • What is the difference "getByText" and "getByTestId" ?

When I had tested react component, There are some gap of that.

Failed In "getByText" code, but it is succeeded in "getByTestId".

I have coded when i was clicked, the color of the title changed to red.

Why this is the difference?

I omitted styled-components of 'Container' and 'Content'. This has props 'toggled' to change color to red.

In "getByText" code.

const { getByText } = render(<ListPresenter content={ListText} />);
const colorChangedText = getByText(/the party/);
fireEvent.click(colorChangedText);
screen.debug(); // The result of render I want !
expect(colorChangedText).toHaveStyle("color: red");    * failed

In "getByTestId" code.

const { getByText } = render(<ListPresenter content={ListText} />);
fireEvent.click(getAllByTestId("list-element-toggle")[0]);
screen.debug(); // The result of render I want !
const colorChangedText = getAllByTestId("list-element-content")[0];
expect(colorChangedText).toHaveStyle("color: red");   * success

Render component...

const Component = (props) => {
  return (
    <Container
        className="container"
        data-testid={"list-element-toggle"}
        toggled={state[data.id - 1]}
     >
        <Content className="content" data-testid={"list-element-content"} toggled={state[data.id - 1]}>
          {data.titleChild}.  // This text had been changed to red color when i was clicked.
        
        </div>
      </div>
  )
}

Aucun commentaire:

Enregistrer un commentaire