testing-library/testing-library-docs

`cleanup` is not automatically called after each test

Closed this issue · 4 comments

The documentation says that cleanup is done automatically.

I have a different experience, however. This test passes:

it('should render page', () => {
	const { getByRole } = render(Page);
	expect(getByRole("heading", { level: 1 }).textContent).toBe("Welcome to SvelteKit");
});

If I add another test after it, that one fails:

it('should have been cleaned up before next test is run', () => {
	const { getByRole } = render(Page);
	expect(getByRole("heading", { level: 1 }).textContent).toBe("Welcome to SvelteKit");
});

The error is:

TestingLibraryElementError: Found multiple elements with the role "heading"

Here are the matching elements:

Ignored nodes: comments, script, style
<h1>
  Welcome to SvelteKit
</h1>

Ignored nodes: comments, script, style
<h1>
  Welcome to SvelteKit
</h1>

(If this is intentional, then use the `*AllBy*` variant of the query (like `queryAllByText`, `getAllByText`, or `findAllByText`)).

If I add this to the top of my file, both tests pass:

import { cleanup } from "@testing-library/svelte";
import { afterEach } from "vitest";
afterEach(() => {
  cleanup();
});

Here is a small repo showcasing the issue: https://github.com/Stadly/reproduction/tree/testing-library/no-cleanup-with-svelte

I ran into this issue as well. In order to avoid it, set globals: true in your vite.config.ts test property.

The code checks if there is a globally available afterEach() function before calling it with cleanup().

The setup documentation includes globals: true, but it's very easy to miss. If the library is going to require this flag in order to work, the documentation should highlight it.

Since it's not a code issue, I'm transferring this to the docs repo :)

mcous commented

@timdeschryver little heads up: I think this issue can be closed! It was resolved by #1360. Vitest setup instructions now include:

  1. Add a vitest-setup.js file to optionally set up automatic post-test cleanup and @testing-library/jest-dom expect matchers.
import '@testing-library/svelte/vitest'
import '@testing-library/jest-dom/vitest'

I'm planning on doing an api.mdx pass sometime this week, so if you'd prefer to keep this issue open until some of that copy can be cleaned up, that works for me, too!

Thanks @mcous :)