2

I have read a few articles suggesting to use custom getByText matchers in order to test text in broken up elements. This does not work in my case. I have a component where I render a 'label' and an amount however, the label is broken up to 2 elements - the colon and text as well as the amount. This makes it terrible for getByText to find it.

export const TotalSummary = ({label, amount}) => {
  const labelId = useUniqueID();

  return (
    <div>
      <span style={{ marginRight: '16px' }} id={labelId}>
        {label ?? 'Total'}:
      </span>
      <span aria-labelledby={labelId}>{amount}</span>
    </div>
  );
};

My test looks as simple as this

it('displays amount and label', () => {
  render(<TotalSummary amount="123" label="Total amount" />);
  expect(screen.getByText(/Total amount: 123/).toBeInTheDocument();
});

This results in a following hierarchy rendered in a test...

<body>
  <div>
    <span style="margin-right: 16px;" id="sb12">
      Total amount
      :
    </span>
    <span aria-labelledby="sb12">
      123
    </span>
  </div>
</body>

...and a failed test error

TestingLibraryElementError: Unable to find an element with the text: /Total amount: 123/. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

I am not sure how to overcome that without testing the label and amount separately which can lead to unexpected test success when the amount or label appears anywhere else on the screen.

2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.