Sunday, April 20, 2025

Hooks - beforeEach, afterEach, beforeAll & afterAll in playwright

 In this example we will explore how to use beforeEach, afterEach, beforeAll, and afterAll hooks in Playwright to streamline your testing process. In Playwright, hooks like beforeEach, afterEach, beforeAll, and afterAll are used to set up and tear down test environments. They help you manage setup tasks like logging in, creating test data, or launching browsers, and cleanup tasks like closing pages or deleting data.

These hooks are part of the Playwright Test Runner and are especially useful when writing test suites with test.describe.

Hooks - beforeEach, afterEach, beforeAll & afterAll in playwright


What Are Hooks?

Hooks are special functions that allow you to run code before or after your tests. They help in setting up the environment or cleaning up resources, ensuring that your tests are isolated and maintainable. Playwright provides several hooks that can be used to manage the lifecycle of your tests.


Types of Hooks :-

  1. beforeEach: Runs before each test in a suite.
  2. afterEach: Runs after each test in a suite.
  3. beforeAll: Runs once before all tests in a suite.
  4. afterAll: Runs once after all tests in a suite.


Using these hooks effectively can reduce code duplication and improve test reliability.


Example -1 :

See the below hook lifecycle in playwright with example. 


beforeEach: This hook runs before each test within the test suite or describe block. It's commonly used for setting up the test environment, such as navigating to a specific page or initializing test data.

afterEach: This hook runs after each test, regardless of whether the test passed or failed. It's typically used for cleaning up the test environment, such as closing the browser or clearing test data.

beforeAll: This hook runs once before all tests within the test suite or describe block. It's suitable for tasks that only need to be done once, such as setting up a database connection or launching a browser instance.

afterAll: This hook runs once after all tests within the test suite or describe block have completed. It's used for cleanup tasks that should only be performed after all tests are finished, such as closing a database connection or shutting down a browser instance.


// @ts-check
import { test, expect } from '@playwright/test';

test.describe('Hooks Example', () => {
    let page;
  
    test.beforeAll(async ({ browser }) => {
      page = await browser.newPage();
      await page.goto('https://www.google.com');
    });
  
    test.beforeEach(async () => {
      console.log('Before each test');
    });
  
    test('Test 1', async () => {
      const url = await page.url();
      console.log(url)
      await expect(page).toHaveURL('https://www.google.com/ ');
    });
  
    test('Test 2', async () => {
      await expect(page.locator('[name="q"]')).toBeVisible();
    });
  
    test.afterEach(async () => {
      console.log('After each test');
    });
  
    test.afterAll(async () => {
      await page.close();
    });
  });

Output :
npx playwright test hooks.spec.js --project=chromium --headed --workers 1

Running 2 tests using 1 worker
[chromium]  tests\screenshots\hooks.spec.js:16:9  Hooks Example  Test 1
Before each test
https://www.google.com/
After each test
[chromium]  tests\screenshots\hooks.spec.js:22:9  Hooks Example  Test 2
Before each test
After each test
  2 passed (4.0s)

Example -2 

In the following example, we use beforeEach to set up a new page and log in before each test, and afterEach to log out and close the page after each test.

const { test, expect } = require("@playwright/test");

let page;

test.beforeEach(async ({ browser }) => {
  page = await browser.newPage();
  await page.goto("https://www.saucedemo.com/v1/");
  await page.locator("id=user-name").fill("standard_user");
  await page.fill("id=password", "secret_sauce");
  await page.click("id=login-button");
});

test("Hooks ", async () => {
  await expect(await page.locator(".product_label")).toBeVisible();
  await page.waitForTimeout(2000);
});

test("Verify header", async () => {
  await expect(await page.locator("#header_container")).toBeVisible();
  await page.waitForTimeout(2000);
});

test.afterEach(async () => {
  await page.locator(".bm-burger-button").click();
  await page.locator("#logout_sidebar_link").click();
  await page.close();
});


Example -3 

In scenarios where you want to perform setup or teardown actions only once for all tests, you can use beforeAll and afterAll. Here’s an example:

const { test, expect } = require("@playwright/test");

let page;

test.beforeAll(async ({ browser }) => {
  page = await browser.newPage();
  await page.goto("https://www.saucedemo.com/v1/");
  await page.locator("id=user-name").fill("standard_user");
  await page.fill("id=password", "secret_sauce");
  await page.click("id=login-button");
});

test("Hooks ", async () => {
  await expect(await page.locator(".product_label")).toBeVisible();
  await page.waitForTimeout(2000);
});

test("Verify header", async () => {
  await expect(await page.locator("#header_container")).toBeVisible();
  await page.waitForTimeout(2000);
});

test.afterAll(async () => {
  await page.locator(".bm-burger-button").click();
  await page.locator("#logout_sidebar_link").click();
  await page.close();
});

Using hooks in Playwright not only enhances the readability of your test code but also improves its maintainability by reducing redundancy.



No comments:

Post a Comment