What is the method to perform teardown or cleanup tasks after all tests in a spec file have run using Playwright Test?


Using afterAll Hook in Playwright Test

When you need to perform cleanup tasks after all tests in a spec file have run, Playwright Test provides the afterAll hook. This hook is executed once per worker process after all tests in a spec file have finished running.

Here's how you can set it up:

import { test } from '@playwright/test';

test.afterAll(async () => {
  // Your cleanup tasks go here

Place this code at the end of your spec file. It ensures that the specified callback function is executed after all tests in that spec file have finished running.

Remember, if you have multiple spec files, each with their own set of tests, the afterAll hook defined in each spec file will run independently after their respective tests. This allows you to perform specific teardown actions for each individual spec file.

Also, Playwright Test uses worker processes for running tests. If a test fails and triggers a restart of the worker process, the afterAll hook will run again in the new worker process. This ensures that any necessary cleanup actions are performed consistently even in case of failures.

For more insights on handling flaky tests and maximizing test efficiency, check out these blog posts on Detecting and Handling Flaky Tests in Playwright and Maximizing Test Efficiency with Parallelism in Playwright.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.