Rayrun
← Back to Discord Forum

Pass data from tests to global teardown

Is it possible to pass data from the tests to the global teardown using projects to be cleaned up?

This thread is trying to answer question "Is it possible to pass data from the tests to the global teardown using projects to be cleaned up?"

8 replies

you could use a worker scoped fixture like an object or array or anything and then during your tests you can mutate the fixture and your cleanup should be able to access the fixture later and use that to clean up

The worker won't be reused for the teardown

Thus the object/array would be empty

It does give me an idea

Since I was only using one worker I used a worker scoped fixture like suggested

Sorry I was not clear enough but you can do cleanup in your worker scoped fixture directly after the await use(..). Is that what you do ?

It's what I am doing now

I did not know that a worker would be restarted in case of test failure (and thus the fixture re-run), trying to see what I can do

Answer

Sure, you can pass data from tests to the global teardown using projects in Playwright. Here's how you can do it:

Setup and Cleanup Projects

First, define a setup project and a cleanup project in your Playwright configuration file (playwright.config.ts). The setup project prepares data or resources for your tests, while the cleanup project tidies up these resources after all tests have run.

// playwright.config.ts
module.exports = {
  projects: [
    {
      name: 'Setup',
      testMatch: /global.setup\.ts/,
    },
    {
      name: 'Cleanup',
      testMatch: /global.cleanup\.ts/,
    },
  ],
};

Project Dependencies

Next, use testProject.dependencies to specify which projects depend on each other. In this case, your cleanup project depends on your setup project.

// playwright.config.ts
module.exports = {
  projects: [
    {
      name: 'Setup',
      testMatch: /global.setup\.ts/,
    },
    {
      name: 'Cleanup',
      testMatch: /global.cleanup\.ts/,
      dependencies: {
        'Setup': { mode: 'before' },
      },
    },
  ],
};

By setting up this dependency relationship, any data or resources set up in the setup project will be accessible in the global teardown.

Remember, using globalSetup and globalTeardown alone won't produce traces or artifacts. If you want to generate traces and artifacts during your testing process, use project dependencies instead.

For more tips on efficient Playwright test scripts, check out this blog post.

Related Discord Threads

TwitterGitHubLinkedIn
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 [email protected].