reactjsreact-testing-libraryvitest

React Testing Library - findByText method from the screen object giving error "TestingLibraryElementError"


I have a React Vite app and using Vitest for testing my application:

I have the below code:

Note.jsx file:

const Note = ({ note, toggleImportance }) => {
  const label = note.important ? 'make not important' : 'make important';

  return (
    <li className="note">
      Your awesome note: {note.content}
      <button onClick={toggleImportance}>{label}</button>
    </li>
  );
};

export default Note;

My test file is Note.test.jsx

test('finds content with findByText', async () => {
    const note = {
      content: 'Does not work anymore',
      important: true
    };

    // the component is rendered with the render function
    render(<Note note={note} />);

    // findByText returns a promise
    const element = await screen.findByText('Does not work anymore');
    screen.debug();

    expect(element).toBeDefined();       
    expect(element).toBeInTheDocument();
    expect(element).toBeVisible();
});

Error:

TestingLibraryElementError: Unable to find an element with the text: Does not work anymore. 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.

Ignored nodes: comments, script, style
<body>
  <div>
    <li
      class="note"
    >
      Your awesome note:
      Does not work anymore
      <button>
        make not important
      </button>
    </li>
  </div>
</body>

Ignored nodes: comments, script, style
<body>
  <div>
    <li
      class="note"
    >
      Your awesome note:
      Does not work anymore
      <button>
        make not important
      </button>
    </li>
  </div>
</body>
 ❯ waitForWrapper node_modules/@testing-library/dom/dist/wait-for.js:163:27
 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:86:33
 ❯ src/components/Note.test.jsx:77:34
     75| 
     76|     // findByText returns a promise
     77|     const element = await screen.findByText('Does not work anymore');
       |                                  ^
     78|     screen.debug();
     79|

The test keeps failing with findByText method. Not sure what I am doing wrong here. Any help would be appreciated.


Solution

  • I got the test to work, I only added the { exact: false } and the test works. The only change is in the Note.test.jsx file:

    const element = await screen.findByText('Does not work anymore', { exact: false });