Search code examples
reactjstestingjestjsreact-testing-library

React Testing Library leaking between tests, DOM persisting


I'm new to testing and I'm trying to figure out how to reset the DOM after each test to make each an isolated test case. In the below code I have simply duplicated a test and the first passes but the second fails with the message: TestingLibraryElementError: Found multiple elements with the placeholder text of: Title

Therefore the test isn't removing the first instance. Is this normal behaviour? And how do I reset between tests? I tried using the cleanup method as found in the jest docs and react testing library docs, but this doesn't work and according to the docs it should be resetting after each test anyway.

import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import TaskList from './TaskList';

describe('TaskList Component', () => {
  it('Adds a new task when the add button is clicked', async () => {
    const user = userEvent.setup();
    const { getByPlaceholderText, getByAltText } = render(<TaskList />);

    const addButton = getByAltText('add');
    await user.click(addButton);

    expect(getByPlaceholderText('Title')).toBeInTheDocument();
  });

  it('Adds a new task when the add button is clicked', async () => {
    const user = userEvent.setup();
    const { getByPlaceholderText, getByAltText } = render(<TaskList />);

    const addButton = getByAltText('add');
    await user.click(addButton);

    expect(getByPlaceholderText('Title')).toBeInTheDocument();
  });
});

I'm using the following packages:

  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^14.0.0",
    "@testing-library/user-event": "^14.4.3",
    "@types/jest": "^29.5.3",
    "@types/react": "^18.0.37",
    "@vitejs/plugin-react": "^4.0.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^29.6.1",
    "jest-environment-jsdom": "^29.6.1",
    "ts-jest": "^29.1.1",
    "ts-node": "^10.9.1",
    "typescript": "^5.0.2",
    "vite": "^4.3.9"
  }

Solution

  • Cleanup is indeed done automatically for Jest + React Testing Library like you mentioned.

    Is it possible that TaskList is rendering multiple items with "Title" as their placeholder text? You might be able to find out by using getAllByPlaceholderText