What is the difference between getByText and getByTestId?
When I had tested a React component, there were some gaps between these two functions.
The test failed in getByText code, but it succeeded in getByTestId.
I have code that when an element 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 the color to red.
Here is the 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
Here is the 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
Here is the rendered 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>
)
}