Rayrun

How do I store global metadata and teardown without restarting the process for different tests in the same file using Playwright?

Answer

Storing Global Metadata and Teardown in Playwright

To store global metadata and teardown without restarting the process for different tests in the same file, you can use project dependencies or the globalSetup option in the configuration file.

Project Dependencies

Project dependencies allow you to define a project that runs before all other projects. This is the recommended way to configure global setup, as it enables the use of fixtures and provides better visibility in HTML reports and trace viewers.

// playwright.config.ts
import { PlaywrightTestConfig } from '@playwright/test';

const config: PlaywrightTestConfig = {
  projects: [
    {
      name: 'Global Setup',
      testDir: 'global-setup',
      testMatch: '**/*.spec.ts',
      use: { storageState: 'global-setup/storage-state.json' },
    },
    {
      name: 'Main Project',
      testDir: 'tests',
      testMatch: '**/*.spec.ts',
      use: { storageState: 'global-setup/storage-state.json' },
      dependsOn: ['Global Setup'],
    },
  ],
};

export default config;

Global Setup Option

Use the globalSetup option in the configuration file to set up something once before running all tests. The globalSetup file must export a single function that takes a config object.

// playwright.config.ts
import { PlaywrightTestConfig } from '@playwright/test';

const config: PlaywrightTestConfig = {
  globalSetup: './global-setup.ts',
  // ...
};

export default config;

In your globalSetup file, you can set environment variables via process.env to make arbitrary data available in your tests.

// global-setup.ts
import { FullConfig } from '@playwright/test';

export default async (config: FullConfig) => {
  // Set up global metadata
  process.env.AUTH_TOKEN = 'your-auth-token';
  // ...
};

To capture a trace of failures during global setup, start tracing in your setup and stop tracing if an error occurs. Wrap your code block inside a try-catch block.

// global-setup.ts
import { FullConfig } from '@playwright/test';

export default async (config: FullConfig) => {
  try {
    // Start tracing
    // Set up global metadata
  } catch (error) {
    // Stop tracing
    throw error;
  }
};

By using project dependencies or the globalSetup option, you can store global metadata and teardown without restarting the process for different tests in the same file.

Thank you!
Was this helpful?
Still have questions?

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

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].