Monday, May 5, 2025

Configure globalSetup and globalTeardown in playwright

In this example we will expore how to configure globalSetup and globalTeardown in Playwright, you need to create a setup file (e.g., global-setup.ts) and a teardown file (e.g., global-teardown.ts), then reference them in the Playwright configuration file (playwright.config.ts). These files handle tasks that run once before and after all tests, such as setting up a test environment or cleaning up resources.

Configure globalSetup and globalTeardown in playwright


Steps to Configure globalSetup and globalTeardown

Project structure

Configure globalSetup and globalTeardown in playwright


1. Create the global-setup.ts

This file runs before all tests. Common use cases include logging in to generate a session or setting up a test database.

import { expect } from '@playwright/test';
import { chromium } from 'playwright';
import { globalState } from './shared';

async function globalSetup() {

  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  
  // Example: login for login page
  await page.goto('https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html');
  await page.locator("id=regUsername").fill("Sumit");
  await page.locator("id=regEmail").fill("Sumit@gmail.com");
  await page.locator("id=regPassword").fill("Skptricks");
  await page.locator("[name=submitregistrationform]").click();
  await expect(page.locator("//h1")).toContainText("405 Not Allowed")
  
  // setting value for shared data accesible within global setup and teardown.
  globalState.data = "Sumit Kumar Pradhan" ;  

  // Access store value  anywhere in project.
  process.env.JWT_Token = 'dad7sd8as8ds8d7asd9';

  // Or a more complicated data structure as JSON:
  process.env.JSON_Data = JSON.stringify({ some: 'data' });
  
  await browser.close();
  console.log("complete the execution for global setup...")

}

export default globalSetup;


2. Create the global-teardown.ts

This file runs after all tests. It’s used for cleanup tasks like closing connections or deleting temporary files.

import { globalState } from './shared';

async function globalTeardown() {

  console.log("Access shared data in teardown : ",globalState.data);
  
  console.log("complete the execution for global teardown...")
}

export default globalTeardown;


3. Create the shared.js

This file helps to store and retrieve data during test execution and we can access data within global setup and teardown files only.

export const globalState = {};

4. Setup configuration in playwright.config.ts or playwright.config.js

Add the below global getting in configuration file
import { defineConfig } from '@playwright/test';

export default defineConfig({
  globalSetup: require.resolve('./global-setup'),
  globalTeardown: require.resolve('./global-teardown'),
  
});


NOTE : when you run your script, then playwright will run the test in following order.

  1. Execute global-setup.ts before any tests.
  2. Run all tests, reusing the session state (if configured).
  3. Execute global-teardown.ts after all tests.


Here is the sample code for the specs file, where we are trying to access stored value in global setup using process.env setting.

// example.spec.js or example.spec.ts
const { test } = require('@playwright/test');
import { globalState } from '../shared.js';

test('example test', async ({browser}) => {
  // Retrieve the browser from the process environment
  
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto('https://www.skptricks.com');

  console.log("Access shared data in global setup - process.env.JWT_Token : ", process.env.JWT_Token);
  console.log("Access shared data in global setup - process.env.JSON_Data : ", process.env.JSON_Data);
  // ... rest of the test
});


Output:

D:\playwright Project\Playwright-tutorial>npx playwright test  global-setup.spec.js --project=chromium --headed
complete the execution for global setup...

Running 1 test using 1 worker

    1 [chromium]  tests\global-setup.spec.js:5:1  example test (4.3s)                                                               
Access shared data in global setup - process.env.JWT_Token :  dad7sd8as8ds8d7asd9
Access shared data in global setup - process.env.JSON_Data :  {"some":"data"}
Access shared data in teardown :  Sumit Kumar Pradhan
complete the execution for global teardown...

  1 passed (7.7s)

This is all about playwright global setup and teardown configuration.


No comments:

Post a Comment