Unable to find an element with the text: /7887/i. This could be because the text is broken up by multiple elements. you can provide a function

Viewed 14

I am testing react app with react testing library and I came cross this error

Unable to find an element with the text: /9900/i. 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 have changed from toBeInTheDocument() to toEqual() but it didn't work too, and I tried to pass a function but it didn't work too?

const getByTextContent = (text) => {
    return screen.getByText((content, element) => {
        const hasText = element => element.textContent === text
        const elementHasText = hasText(element)
        const childrenDontHaveText = Array.from(element?.children || []).every(child => !hasText(child))
        return elementHasText && childrenDontHaveText
  })
}

Here is the test

  expect(dataFetcher).toBeCalledTimes(1);
  await waitFor(() => {
    const playerId = screen.getByText(/9900/i);
    expect(playerId.value).toEqual(9900);
    expect(playerId).toBeInTheDocument();  // I tried this too but ogt the same result
  });
1 Answers

I worked around this in my code logic by passing ? to safely access the object property, like this {candidateData && candidateData[i]?.name}, and not in the test file. but I got this warning. I am wondering why this is happening

      Warning: An update to Scorecard inside a test was not wrapped in act(...).

      When testing, code that causes React state updates should be wrapped into act(...):

      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */
Related