31

I'm having trouble finding the correct way to test a div with text that is broken up by multiple elements - the error says 'Unable to find an element with the text: This could be because the text is broken up by multiple elements' but doesn't explain how to do so.

To explain what I'm trying to test, the element returned in the jest render() fn is as followed:

          <div>
            <div
              class="inventory-wrapper"
            >
              <span>
                5
              </span>
               item
              s
               left
            </div>
          </div>
        </body>

I'm trying to test that the text inside is '5 items left', but as you can see - the text is broken up by a span tag and multiple lines.

From what I understand, I should be targeting this with getByRole() only? Does that mean I need to add a role='...' to the .inventory-wrapper div too? And how would I then test for the text '5 items left'

Any help on the correct wait to target something like this would be very appreciated

0

3 Answers 3

14
it('your test case', () => {
  expect.assertions(1);
  render(<Component/>)
  expect(screen.getByText((_, element) => element.textContent === 'some text')).toBeInTheDocument();
});

where element.textContent returns the text content of the element. Then you can work with it the way you want. You can try to check if it's equal === something or match etc. This is one of few ways to work with multiline text.

P.S. screen is more preferable than getByTestId.

Sign up to request clarification or add additional context in comments.

Comments

5

Getting by role might be preferred but isn't the only way to query the DOM.

I worked around this by adding a test id to the component, querying that and using its text content. Just make sure the test id is passed to the root element in the component.

render(<Component data-testid="component" />)
expect(screen.getByTestId('component').textContent).toBe('Text to test')

Comments

0

Complete example

Suppose you have a HeaderComponent

 export const TestIdHeaderComponent = 'headerId";


  <HeaderComponent
      data-testid={TestIdHeaderComponent}
    >
      { "My Awesome Header"}
   </HeaderComponent>

You can test it like this

 const hederComponent = screen.queryByTestId(TestIdHeaderComponent);
    expect(hederComponent).toBeInTheDocument();
    expect(hederComponent?.textContent).toBe("My Awesome Header");

    // or 
    expect(screen.getByTestId(TestIdHeaderComponent).textContent).toBe(
      "My Awesome Header",
    );

Comments

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.