Playwright Test Hooks Interview Questions and Answers (2026): Beginner to Advanced Guide

1. Introduction: Importance of Playwright Hooks in Automation Testing

Playwright is a modern automation testing framework used to automate web applications across Chromium, Firefox, and WebKit browsers. It provides powerful features such as browser automation, automatic waiting, parallel execution, API testing, fixtures, and test hooks.

One important topic frequently discussed in technical interviews is Playwright test hooks.

When automation engineers develop large test suites, they often need to perform common operations before and after test execution. For example, opening an application, logging into an account, creating test data, clearing database records, and closing resources.

Writing these operations repeatedly inside every test case makes the automation framework difficult to maintain.

Playwright solves this problem through test hooks.

The most commonly used Playwright hooks are:

  • test.beforeEach()
  • test.afterEach()
  • test.beforeAll()
  • test.afterAll()

Interviewers ask Playwright test hooks interview questions to evaluate whether candidates understand test execution order, lifecycle management, test isolation, parallel execution, and resource cleanup.

For freshers, understanding the basic hook syntax is important. For experienced QA Automation Engineers and Senior SDETs, interviewers expect knowledge of hooks in enterprise frameworks, fixtures, API setup, database cleanup, and CI/CD execution.

This guide covers practical Playwright hooks interview questions and answers with runnable TypeScript examples, real-time scenarios, troubleshooting techniques, and placement-focused preparation tips.

2. What Are Test Hooks in Playwright?

Test hooks are special functions provided by Playwright Test that execute at specific stages of the test lifecycle.

They allow automation engineers to execute common setup and cleanup operations without repeating the same code in every test.

For example:

import { test, expect } from ‘@playwright/test’;

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

});

test(‘Verify homepage’, async ({ page }) => {

  await expect(page).toHaveTitle(‘Example Domain’);

});

test(‘Verify heading’, async ({ page }) => {

  await expect(page.locator(‘h1’))

    .toHaveText(‘Example Domain’);

});

In this example:

  1. beforeEach() executes before every test.
  2. The browser page navigates to the application.
  3. The first test validates the page title.
  4. The second test validates the heading.

The navigation operation is written only once, making the test code easier to maintain.

Benefits of Playwright Test Hooks

  1. Code reusability: Common setup operations can be reused across multiple test cases.
  2. Maintainability: Changes to common setup logic can be managed centrally.
  3. Test isolation: Each test can receive its own browser context and test data.
  4. Resource management: Cleanup operations can be performed after tests.
  5. Better organization: Setup, execution, and cleanup responsibilities are separated.
  6. Framework scalability: Hooks help organize large automation suites.

3. Types of Playwright Hooks

Playwright Test provides four commonly used lifecycle hooks.

3.1 beforeEach()

beforeEach() executes before every test in its applicable scope.

It is commonly used for:

  • Opening the application.
  • Navigating to a specific URL.
  • Initializing test data.
  • Performing common setup operations.
  • Preparing the test environment.

Example:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

});

If a test file contains three tests, the hook executes three times.

3.2 afterEach()

afterEach() executes after every test in its applicable scope.

It is commonly used for:

  • Logging out.
  • Cleaning up test data.
  • Resetting application state.
  • Recording test execution information.
  • Releasing test-specific resources.

Example:

test.afterEach(async ({ page }) => {

  console.log(‘Test execution completed’);

});

It runs after each test, including tests that fail, subject to the test runner’s execution and interruption behavior.

3.3 beforeAll()

beforeAll() executes once before the tests in its applicable scope within a worker process.

It is commonly used for:

  • Creating shared test data.
  • Starting external test services.
  • Preparing worker-level resources.
  • Performing expensive setup operations.

Example:

test.beforeAll(async () => {

  console.log(‘Starting test execution’);

});

Important: beforeAll() does not receive the normal test-scoped page fixture. If a browser page is required, create and manage a browser context and page explicitly.

3.4 afterAll()

afterAll() executes after the tests in its applicable scope have completed within a worker process.

It is commonly used for:

  • Closing manually created browser contexts.
  • Removing shared test data.
  • Stopping test services.
  • Releasing shared resources.

Example:

test.afterAll(async () => {

  console.log(‘All tests in this scope completed’);

});

Important: In parallel execution, worker-level hooks can execute separately in different workers. If a worker restarts after a failure, its beforeAll() may run again.

4. Playwright Test Lifecycle and Execution Order

Understanding hook execution order is one of the most frequently asked topics in Playwright test hooks interview questions.

Consider the following example:

import { test } from ‘@playwright/test’;

test.beforeAll(async () => {

  console.log(‘Before All’);

});

test.beforeEach(async () => {

  console.log(‘Before Each’);

});

test.afterEach(async () => {

  console.log(‘After Each’);

});

test.afterAll(async () => {

  console.log(‘After All’);

});

test(‘Test 1’, async () => {

  console.log(‘Executing Test 1’);

});

test(‘Test 2’, async () => {

  console.log(‘Executing Test 2’);

});

Expected execution order:

Before All

Before Each

Executing Test 1

After Each

Before Each

Executing Test 2

After Each

After All

Hook Execution Order in Nested describe Blocks

Playwright supports nested test.describe() blocks.

For nested groups:

  • Outer beforeAll() runs before inner beforeAll().
  • Outer beforeEach() runs before inner beforeEach().
  • Inner afterEach() runs before outer afterEach().
  • Inner afterAll() runs before outer afterAll().

Example:

test.beforeEach(async () => {

  console.log(‘Outer Before Each’);

});

test.describe(‘Login Tests’, () => {

  test.beforeEach(async () => {

    console.log(‘Inner Before Each’);

  });

  test(‘Verify login’, async () => {

    console.log(‘Test Execution’);

  });

  test.afterEach(async () => {

    console.log(‘Inner After Each’);

  });

});

test.afterEach(async () => {

  console.log(‘Outer After Each’);

});

Expected order:

Outer Before Each

Inner Before Each

Test Execution

Inner After Each

Outer After Each

This execution order is important when designing reusable test frameworks.

5. Basic Playwright Test Hooks Interview Questions and Answers

These questions are suitable for freshers and candidates with basic knowledge of automation testing.

Q1. What are test hooks in Playwright?

Interview-Ready Answer:

Test hooks are lifecycle functions that execute before or after test cases. They help manage common setup and cleanup operations.

Explanation:

Playwright provides beforeEach(), afterEach(), beforeAll(), and afterAll().

TypeScript Code Example:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

});

Interview Tip: Explain how hooks reduce duplicate code in automation frameworks.

Q2. What are the different types of hooks in Playwright?

Interview-Ready Answer:

Playwright Test provides four main hooks: beforeEach, afterEach, beforeAll, and afterAll.

Explanation:

  • beforeEach: Runs before each test.
  • afterEach: Runs after each test.
  • beforeAll: Runs once per applicable scope and worker.
  • afterAll: Runs after the tests in that scope and worker.

TypeScript Code Example:

test.beforeAll(async () => {

  console.log(‘Before all tests’);

});

test.beforeEach(async () => {

  console.log(‘Before each test’);

});

test.afterEach(async () => {

  console.log(‘After each test’);

});

test.afterAll(async () => {

  console.log(‘After all tests’);

});

Interview Tip: Be prepared to explain the difference between per-test and per-worker execution.

Q3. What is beforeEach() in Playwright?

Interview-Ready Answer:

beforeEach() is a hook that executes before every test case in its applicable scope.

Explanation:

It is useful for navigating to the application, preparing common test data, and initializing test-specific conditions.

TypeScript Code Example:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com/login’);

});

Interview Tip: Mention that each test normally receives its own isolated page fixture.

Q4. What is afterEach() in Playwright?

Interview-Ready Answer:

afterEach() executes after every test case in its applicable scope.

Explanation:

It is commonly used for cleaning up test-specific resources and resetting application state.

TypeScript Code Example:

test.afterEach(async ({ page }) => {

  console.log(‘Test completed’);

});

Interview Tip: Explain how cleanup helps prevent test data from affecting subsequent tests.

Q5. What is beforeAll() in Playwright?

Interview-Ready Answer:

beforeAll() executes once before the tests in its applicable scope within a worker process.

Explanation:

It is useful for expensive shared setup operations. It should not be confused with beforeEach(), which runs before every test.

TypeScript Code Example:

test.beforeAll(async () => {

  console.log(‘Initialize shared resources’);

});

Interview Tip: Remember that beforeAll() cannot directly use the normal test-scoped page fixture.

Q6. What is afterAll() in Playwright?

Interview-Ready Answer:

afterAll() executes after the tests in its applicable scope have completed within a worker process.

Explanation:

It is useful for closing shared resources and removing shared test data.

TypeScript Code Example:

test.afterAll(async () => {

  console.log(‘Release shared resources’);

});

Interview Tip: Explain why resource cleanup is important in large automation projects.

Q7. Why do we use Playwright hooks?

Interview-Ready Answer:

We use hooks to organize reusable setup and teardown operations, reduce duplicate code, and maintain consistent test execution.

Explanation:

Instead of repeating login navigation or test environment preparation in every test, we can centralize common operations.

TypeScript Code Example:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

});

Interview Tip: Give examples from a login, registration, or checkout workflow.

Q8. Can we use multiple hooks in a single test file?

Interview-Ready Answer:

Yes. We can define multiple hooks in a test file and organize them inside different test.describe() blocks.

Explanation:

Hooks can have different scopes and responsibilities.

TypeScript Code Example:

test.beforeAll(async () => {

  console.log(‘Suite setup’);

});

test.beforeEach(async () => {

  console.log(‘Test setup’);

});

test(‘Test 1’, async () => {

  console.log(‘First test’);

});

test(‘Test 2’, async () => {

  console.log(‘Second test’);

});

Interview Tip: Explain hook scope and execution order rather than simply saying multiple hooks are supported.

Q9. Can we write hooks inside test.describe()?

Interview-Ready Answer:

Yes. Hooks can be defined inside a test.describe() block to apply them only to the tests belonging to that group.

Explanation:

This is useful when different application modules require different setup operations.

TypeScript Code Example:

test.describe(‘Login Module’, () => {

  test.beforeEach(async ({ page }) => {

    await page.goto(‘https://example.com/login’);

  });

  test(‘Verify login page’, async ({ page }) => {

    await expect(page.locator(‘#username’))

      .toBeVisible();

  });

});

Interview Tip: Explain that describe-level hooks help organize module-specific test setup.

Q10. What happens if a beforeEach() hook fails?

Interview-Ready Answer:

If a beforeEach() hook fails, Playwright does not execute the corresponding test body. It reports the failure and performs applicable teardown operations.

Explanation:

The test cannot continue normally because its required setup was unsuccessful. The test runner also handles applicable cleanup and subsequent tests according to its execution strategy.

TypeScript Code Example:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

  await expect(page.locator(‘#application-ready’))

    .toBeVisible();

});

test(‘Verify dashboard’, async ({ page }) => {

  await expect(page.locator(‘.dashboard’))

    .toBeVisible();

});

Interview Tip: Mention that a failed setup should be investigated instead of allowing tests to run against an unprepared application.

6. Intermediate Playwright Hooks Interview Questions and Answers

These questions are suitable for candidates with 2–3 years of automation testing experience.

Q11. What is the difference between beforeEach() and beforeAll()?

Interview-Ready Answer:

beforeEach() executes before every test, whereas beforeAll() executes once per applicable scope within a worker process.

Comparison Table:

FeaturebeforeEach()beforeAll()
ExecutionBefore every testOnce per scope and worker
Main purposeTest-specific setupShared setup
FrequencyMultiple timesUsually once per worker
Page fixtureAvailableNot available as a test-scoped fixture
Common useNavigation and test dataShared resources

TypeScript Code Example:

test.beforeAll(async () => {

  console.log(‘Create shared resources’);

});

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

});

Explanation:

Shared resources are prepared once, while each test receives its own setup.

Interview Tip: Mention that beforeAll() is not necessarily once for the entire test run when parallel workers are involved.

Q12. What is the difference between afterEach() and afterAll()?

Interview-Ready Answer:

afterEach() executes after every test, whereas afterAll() executes after all tests in its applicable scope within a worker.

TypeScript Code Example:

test.afterEach(async () => {

  console.log(‘Clean test-specific data’);

});

test.afterAll(async () => {

  console.log(‘Clean shared resources’);

});

Explanation:

Use afterEach() for individual test cleanup and afterAll() for shared resource cleanup.

Interview Tip: Give an example involving temporary user accounts and shared test infrastructure.

Q13. Can we access the page fixture inside beforeAll()?

Interview-Ready Answer:

No. The standard test-scoped page fixture is not available directly inside beforeAll().

Explanation:

Playwright creates isolated page and browser context fixtures for individual tests. If a shared page is genuinely required, it must be created and managed manually using the worker-scoped browser fixture.

TypeScript Code Example:

let sharedPage;

test.beforeAll(async ({ browser }) => {

  const context = await browser.newContext();

  sharedPage = await context.newPage();

  await sharedPage.goto(‘https://example.com’);

});

For a complete implementation, retain the context and close it in afterAll():

let context;

let sharedPage;

test.beforeAll(async ({ browser }) => {

  context = await browser.newContext();

  sharedPage = await context.newPage();

  await sharedPage.goto(‘https://example.com’);

});

test.afterAll(async () => {

  await context.close();

});

Interview Tip: Prefer isolated test fixtures for normal UI tests. Shared pages can introduce state leakage between tests.

Q14. Can we use async and await inside Playwright hooks?

Interview-Ready Answer:

Yes. Playwright hooks support asynchronous operations using async and await.

Explanation:

Most browser operations, API requests, and database operations are asynchronous.

TypeScript Code Example:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

  await page.locator(‘#username’)

    .fill(‘admin’);

});

Interview Tip: Always await asynchronous setup and cleanup operations to prevent unexpected execution behavior.

Q15. Can we pass fixtures to Playwright hooks?

Interview-Ready Answer:

Yes. Hooks can receive fixtures through their callback arguments.

Explanation:

Fixtures provide reusable resources such as page, browser, context, and request.

TypeScript Code Example:

test.beforeEach(async ({ page, request }) => {

  await page.goto(‘https://example.com’);

  const response = await request.get(

    ‘https://jsonplaceholder.typicode.com/posts/1’

  );

  expect(response.status()).toBe(200);

});

Interview Tip: Explain how fixtures and hooks work together to manage test dependencies.

Q16. Can hooks be defined inside nested describe blocks?

Interview-Ready Answer:

Yes. Hooks can be defined in nested test.describe() blocks, and their execution follows the parent-child lifecycle order.

TypeScript Code Example:

test.beforeEach(async () => {

  console.log(‘Parent setup’);

});

test.describe(‘Payment Tests’, () => {

  test.beforeEach(async () => {

    console.log(‘Payment setup’);

  });

  test(‘Verify payment’, async () => {

    console.log(‘Payment test’);

  });

});

Explanation:

The parent setup executes before the child setup.

Interview Tip: Remember that after-hooks execute in reverse nesting order.

Q17. Do Playwright hooks execute when a test fails?

Interview-Ready Answer:

Yes. Applicable teardown hooks such as afterEach() and afterAll() are normally executed when tests fail, subject to worker termination, interruption, and cleanup behavior.

Explanation:

Teardown operations help release resources and maintain the test environment.

TypeScript Code Example:

test.afterEach(async () => {

  console.log(‘Cleanup after test’);

});

Interview Tip: Avoid assuming cleanup is guaranteed after process termination or infrastructure failure. Design cleanup to be safe and repeatable.

Q18. Can we skip tests using hooks?

Interview-Ready Answer:

Yes. Playwright provides test annotations such as test.skip() and conditional skipping inside hooks.

Explanation:

Conditional skipping is useful when a test is not applicable to a particular browser, environment, or configuration.

TypeScript Code Example:

test.beforeEach(async ({ browserName }) => {

  test.skip(

    browserName === ‘webkit’,

    ‘Not supported in this environment’

  );

});

Interview Tip: Use conditional skipping only when there is a genuine requirement. Do not hide actual test failures by skipping them.

Q19. What is the difference between hooks and fixtures in Playwright?

Interview-Ready Answer:

Hooks define when setup and teardown operations execute. Fixtures provide reusable resources and control their initialization and cleanup lifecycle.

Comparison Table:

FeatureHooksFixtures
PurposeLifecycle managementResource management
ExamplesbeforeEach, afterAllpage, context, request
ReusabilityCommon setup operationsReusable dependencies
CleanupafterEach, afterAllFixture teardown
CustomizationHook callbacksCustom fixture definitions

TypeScript Code Example:

import { test as base } from ‘@playwright/test’;

type MyFixtures = {

  appUrl: string;

};

const test = base.extend<MyFixtures>({

  appUrl: async ({}, use) => {

    await use(‘https://example.com’);

  }

});

test.beforeEach(async ({ page, appUrl }) => {

  await page.goto(appUrl);

});

Explanation:

The custom fixture provides the application URL, while the hook uses it before each test.

Interview Tip: Explain that fixtures are often a better choice for reusable dependencies, while hooks are useful for organizing lifecycle actions.

7. Advanced and Scenario-Based Playwright Hooks Interview Questions

These questions help evaluate practical knowledge for experienced QA Automation Engineers and Senior SDETs.

Q20. How do Playwright hooks behave during parallel execution?

Interview-Ready Answer:

Playwright executes tests across worker processes. Worker-level hooks such as beforeAll() and afterAll() execute independently within their respective workers.

Explanation:

If a test file is distributed across multiple workers, its beforeAll() hook can execute once in each worker that runs tests from that file.

TypeScript Code Example:

test.beforeAll(async ({}, testInfo) => {

  console.log(

    ‘Worker:’,

    testInfo.workerIndex

  );

});

test(‘Test 1’, async () => {

  console.log(‘Executing Test 1’);

});

test(‘Test 2’, async () => {

  console.log(‘Executing Test 2’);

});

Interview Tip: Explain why shared database records and global test data must be managed carefully during parallel execution.

Q21. What happens if beforeAll() fails?

Interview-Ready Answer:

If beforeAll() fails, Playwright cannot execute the tests that depend on that setup in the affected scope and worker. It reports the failure and performs applicable teardown.

Explanation:

A failed shared setup can affect multiple tests, so it should be used only for genuinely shared prerequisites.

TypeScript Code Example:

test.beforeAll(async () => {

  throw new Error(‘Environment initialization failed’);

});

Interview Tip: Keep shared setup simple and avoid making unrelated tests depend on unnecessary external services.

Q22. Can we use API calls inside beforeEach()?

Interview-Ready Answer:

Yes. We can use the request fixture inside beforeEach() to create test data or prepare backend conditions.

TypeScript Code Example:

test.beforeEach(async ({ request }) => {

  const response = await request.post(

    ‘https://example.com/api/users’,

    {

      data: {

        name: ‘Test User’,

        role: ‘Admin’

      }

    }

  );

  expect(response.status()).toBe(201);

});

Explanation:

The API creates a test user before the UI test starts.

Interview Tip: API-based setup is often faster than creating all test data through the UI.

Q23. How do you implement login using Playwright hooks?

Interview-Ready Answer:

For a simple framework, I can use beforeEach() to perform login before every test. For larger frameworks, I prefer authentication setup projects and reusable storage state to avoid repeating the login workflow.

TypeScript Code Example:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com/login’);

  await page.locator(‘#username’)

    .fill(‘admin’);

  await page.locator(‘#password’)

    .fill(‘admin123’);

  await page.getByRole(‘button’, {

    name: ‘Login’

  }).click();

  await expect(page).toHaveURL(/dashboard/);

});

Explanation:

Every test starts with an authenticated session.

Interview Tip: Discuss the trade-off between repeated UI login and storage-state authentication. Never hardcode production credentials in test scripts.

Q24. How do you clean up test data using afterEach()?

Interview-Ready Answer:

I use an API request or database utility to remove the records created during test execution.

TypeScript Code Example:

test.afterEach(async ({ request }) => {

  const response = await request.delete(

    ‘https://example.com/api/test-data’

  );

  expect(response.status()).toBe(200);

});

Explanation:

The cleanup request removes temporary test data after each test. In a real framework, cleanup should target only the records created by that test.

Interview Tip: Use unique test data identifiers to prevent parallel tests from deleting each other’s records.

Q25. How do you handle database cleanup in Playwright hooks?

Interview-Ready Answer:

I use a reusable database utility or backend cleanup API to remove test records after execution. I keep database operations separate from UI page objects.

Explanation:

This avoids coupling database logic with browser interaction code.

TypeScript Code Example:

test.afterEach(async () => {

  await database.cleanupTestUser(

    ‘automation-test-user’

  );

});

Here, database.cleanupTestUser() represents a project-specific database utility that must be implemented and imported.

Interview Tip: In enterprise frameworks, discuss transactions, unique test records, environment permissions, and safe cleanup.

Q26. Can we configure browser settings using hooks?

Interview-Ready Answer:

Browser context settings are generally configured through Playwright’s use configuration or through a manually created browser context. Hooks can prepare additional browser-related setup when necessary.

TypeScript Code Example:

test.beforeEach(async ({ page }) => {

  await page.setViewportSize({

    width: 1366,

    height: 768

  });

  await page.goto(‘https://example.com’);

});

Explanation:

The viewport is configured before navigating to the application.

Interview Tip: Prefer Playwright configuration for settings that should remain consistent across the entire project.

Q27. What happens if afterEach() fails?

Interview-Ready Answer:

Playwright reports the teardown failure and marks the test as failed, even if its test body passed.

Explanation:

Cleanup is an important part of reliable automation. A failed cleanup can leave unwanted records or resources behind.

TypeScript Code Example:

test.afterEach(async () => {

  const cleanupSuccessful = false;

  if (!cleanupSuccessful) {

    throw new Error(‘Test cleanup failed’);

  }

});

Interview Tip: Make cleanup operations idempotent so they can safely handle already-deleted or missing resources.

Q28. How do hooks work with retries in Playwright?

Interview-Ready Answer:

When a test fails and Playwright retries it, the retry is executed in a new worker process. The relevant setup hooks run again for the retried test.

Explanation:

Playwright restarts the worker after a test failure when retries are enabled. This means worker-level setup can execute again.

TypeScript Code Example:

import { defineConfig } from ‘@playwright/test’;

export default defineConfig({

  retries: 2

});

Interview Tip: Make setup and cleanup operations repeatable. Never assume shared resources will survive a worker restart.

Q29. How would you organize hooks in a large Playwright framework?

Interview-Ready Answer:

I organize hooks based on test scope and business functionality. Global setup is used for project-level initialization, fixtures handle reusable resources, and describe-level hooks handle module-specific setup.

TypeScript Code Example:

test.describe(‘User Management’, () => {

  test.beforeEach(async ({ page }) => {

    await page.goto(‘/users’);

  });

  test.afterEach(async ({ request }) => {

    await request.delete(‘/api/test-users’);

  });

  test(‘Verify user list’, async ({ page }) => {

    await expect(page.locator(‘.user-list’))

      .toBeVisible();

  });

});

Explanation:

The setup and cleanup operations apply only to the user management test group.

Interview Tip: Explain how you avoid duplicating hooks across multiple test files by using custom fixtures and shared utilities.

8. Practical TypeScript Code Examples for Each Playwright Hook

This section provides a complete example that demonstrates all four Playwright hooks.

Example 1: beforeEach() and afterEach()

import { test, expect } from ‘@playwright/test’;

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com/login’);

  console.log(‘Application opened’);

});

test.afterEach(async ({ page }) => {

  console.log(‘Test completed’);

});

test(‘Verify login page’, async ({ page }) => {

  await expect(page.locator(‘h1’))

    .toBeVisible();

});

test(‘Verify page title’, async ({ page }) => {

  await expect(page)

    .toHaveTitle(‘Example Domain’);

});

Expected execution:

  • beforeEach() runs before the first test.
  • The first test executes.
  • afterEach() runs.
  • beforeEach() runs before the second test.
  • The second test executes.
  • afterEach() runs again.

Example 2: beforeAll() and afterAll() with Browser Context

import { test, expect } from ‘@playwright/test’;

let context;

let page;

test.beforeAll(async ({ browser }) => {

  context = await browser.newContext();

  page = await context.newPage();

  await page.goto(‘https://example.com’);

});

test(‘Verify heading’, async () => {

  await expect(page.locator(‘h1’))

    .toHaveText(‘Example Domain’);

});

test.afterAll(async () => {

  await context.close();

});

Explanation:

This example manually creates a shared browser context and page for tests in the scope.

The context is closed after the tests finish.

Important: This is a demonstration of worker-level resource management, not the recommended default for independent UI tests. Sharing a page can cause test interference. Prefer the standard page fixture for isolated test execution.

Example 3: API Setup Using beforeEach()

import { test, expect } from ‘@playwright/test’;

test.beforeEach(async ({ request }) => {

  const response = await request.post(

    ‘https://example.com/api/users’,

    {

      data: {

        name: ‘Automation User’

      }

    }

  );

  expect(response.status()).toBe(201);

});

test(‘Verify user management’, async ({ page }) => {

  await page.goto(‘https://example.com/users’);

  await expect(page.locator(‘.user-list’))

    .toBeVisible();

});

Explanation:

The API request creates test data before the UI validation begins.

Example 4: Authentication Using Storage State

For larger frameworks, authentication can be handled through a setup project instead of logging in through beforeEach() for every test.

Example setup:

import { test as setup, expect } from ‘@playwright/test’;

setup(‘Authenticate user’, async ({ page }) => {

  await page.goto(‘https://example.com/login’);

  await page.locator(‘#username’)

    .fill(process.env.TEST_USERNAME!);

  await page.locator(‘#password’)

    .fill(process.env.TEST_PASSWORD!);

  await page.getByRole(‘button’, {

    name: ‘Login’

  }).click();

  await expect(page).toHaveURL(/dashboard/);

  await page.context().storageState({

    path: ‘playwright/.auth/user.json’

  });

});

Configure the authenticated project to reuse the storage state:

import { defineConfig } from ‘@playwright/test’;

export default defineConfig({

  use: {

    baseURL: ‘https://example.com’,

    storageState: ‘playwright/.auth/user.json’

  }

});

The setup project must be configured as a dependency of the authenticated test project. Also, protect the authentication state file because it may contain sensitive session information.

9. Real-World Playwright Hook Scenarios

Here are practical situations interviewers may ask about.

ScenarioRecommended approach
Open application before every testbeforeEach()
Clear test data after every testafterEach()
Initialize shared worker resourcebeforeAll()
Close manually created shared contextafterAll()
Prepare API test databeforeEach() or fixture
Authenticate once for multiple testsSetup project and storage state
Clean database recordsCleanup fixture or afterEach()
Configure viewportPlaywright use configuration
Handle parallel test executionIsolated fixtures and unique test data
Start an external test serviceGlobal setup or worker fixture

Enterprise Playwright Framework Structure

A maintainable automation framework can use the following folder structure:

playwright-project/

│

├── tests/

│   ├── login.spec.ts

│   ├── user.spec.ts

│   └── payment.spec.ts

│

├── fixtures/

│   └── custom-fixtures.ts

│

├── hooks/

│   └── test-hooks.ts

│

├── pages/

│   ├── LoginPage.ts

│   └── DashboardPage.ts

│

├── utils/

│   ├── DatabaseUtils.ts

│   └── ApiUtils.ts

│

├── playwright/

│   └── .auth/

│

└── playwright.config.ts

Framework design recommendation:

  • Keep browser interaction inside page objects.
  • Keep reusable dependencies inside fixtures.
  • Keep common lifecycle operations in appropriate hooks.
  • Keep API and database utilities separate.
  • Use environment variables for credentials.
  • Use unique test data for parallel execution.
  • Configure traces and reports for CI/CD.

This structure helps automation teams maintain large Playwright projects.

10. Common Playwright Hooks Mistakes and Troubleshooting

Understanding common mistakes is important for writing stable automation scripts.

Mistake 1: Using page fixture inside beforeAll()

Incorrect:

test.beforeAll(async ({ page }) => {

  await page.goto(‘https://example.com’);

});

Why is it incorrect?

The normal page fixture is test-scoped and cannot be used directly in beforeAll().

Solution:

Use page inside beforeEach() or create a browser context manually in beforeAll() when shared browser resources are genuinely required.

Mistake 2: Using beforeAll() for test-specific data

If every test requires a different user account, creating one shared account in beforeAll() can cause conflicts.

Solution: Create unique test data using beforeEach() or a custom fixture.

Mistake 3: Forgetting await in hooks

Incorrect:

test.beforeEach(async ({ page }) => {

  page.goto(‘https://example.com’);

});

Correct:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

});

Without await, the setup operation may not complete before the test continues.

Mistake 4: Sharing browser state between parallel tests

Sharing one page between multiple tests can cause unexpected navigation and state changes.

Solution: Use Playwright’s isolated page fixture for independent tests.

Mistake 5: Writing expensive operations in every beforeEach()

Repeatedly creating expensive resources can increase execution time.

Solution: Evaluate whether a worker-scoped fixture or setup project is more appropriate.

Mistake 6: Ignoring cleanup failures

Failed cleanup can leave unwanted test data in the environment.

Solution: Use reliable cleanup utilities, unique identifiers, and appropriate error handling.

11. Playwright Hooks Best Practices

Follow these practices when developing professional automation frameworks.

  1. Use beforeEach() for test-specific setup.
  2. Use afterEach() for test-specific cleanup.
  3. Use beforeAll() for shared worker-level setup.
  4. Use afterAll() for releasing shared worker-level resources.
  5. Prefer fixtures for reusable resource management.
  6. Avoid sharing pages between independent tests.
  7. Keep setup and teardown operations asynchronous and properly awaited.
  8. Use unique test data for parallel execution.
  9. Make cleanup operations safe and repeatable.
  10. Avoid unnecessary login operations in every test when storage-state authentication is appropriate.
  11. Use global setup only for genuinely project-wide initialization.
  12. Configure appropriate timeouts for slow setup operations.
  13. Capture traces and screenshots for CI/CD failures.
  14. Never hardcode sensitive credentials.
  15. Keep hooks small and focused on one responsibility.

12. Playwright Hooks vs Selenium, TestNG, and JUnit Hooks

Candidates transitioning from Selenium frequently ask about the differences between Playwright and traditional Java automation frameworks.

PlaywrightTestNGJUnit 5Purpose
beforeEach()@BeforeMethod@BeforeEachBefore every test
afterEach()@AfterMethod@AfterEachAfter every test
beforeAll()@BeforeClass@BeforeAllBefore test group/class
afterAll()@AfterClass@AfterAllAfter test group/class

Q30. What is the difference between Playwright hooks and TestNG annotations?

Interview-Ready Answer:

Both Playwright hooks and TestNG annotations manage test lifecycle operations. Playwright uses JavaScript/TypeScript callback functions, whereas TestNG uses Java annotations.

Explanation:

For example, Playwright’s beforeEach() performs a similar lifecycle role to TestNG’s @BeforeMethod.

TypeScript Code Example:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

});

Interview Tip: When transitioning from Selenium to Playwright, explain the lifecycle concept rather than comparing only the syntax.

Q31. What is the difference between Playwright hooks and Selenium setup methods?

Interview-Ready Answer:

Selenium commonly uses TestNG or JUnit annotations to manage setup and teardown. Playwright Test provides its own built-in lifecycle hooks and fixture management.

Explanation:

Playwright integrates browser contexts, pages, and test isolation into its fixture system.

TypeScript Code Example:

test.beforeEach(async ({ page }) => {

  await page.goto(‘https://example.com’);

});

Interview Tip: Highlight Playwright’s built-in fixtures and browser-context isolation.

13. Frequently Asked Questions About Playwright Test Hooks

1. What are the benefits of Playwright test hooks?

Playwright hooks reduce duplicate code, improve test organization, simplify setup and cleanup, and make automation frameworks easier to maintain.

2. What is Playwright test hooks interview questions?

Playwright test hooks interview questions are technical questions that evaluate knowledge of lifecycle hooks, setup and teardown operations, execution order, fixtures, parallel execution, and resource management.

3. Is Playwright test hooks interview questions suitable for beginners?

Yes. Beginners can start with beforeEach(), afterEach(), beforeAll(), and afterAll() before learning advanced concepts such as fixtures and parallel execution.

4. Which Playwright hook executes before every test?

beforeEach() executes before every test in its applicable scope.

5. Which Playwright hook executes only once?

beforeAll() executes once within its applicable scope per worker process, rather than once per individual test.

6. Can we use multiple beforeEach hooks?

Yes. Multiple hooks can be defined in applicable scopes. Their execution follows the scope and registration order.

7. Can beforeAll() be used for login?

Yes, but a shared browser page is not always the best approach. For reusable authentication, storage state and setup projects are generally preferable.

8. Can we use API requests inside Playwright hooks?

Yes. The request fixture can be used in test-scoped hooks such as beforeEach() and afterEach().

9. Do hooks work with parallel execution?

Yes. However, worker-level hooks execute independently in workers. Shared test data must be designed to avoid conflicts.

10. What happens if afterEach() fails?

Playwright reports the teardown failure and marks the test as failed, even if the test body passed.

11. Can we use hooks inside describe blocks?

Yes. Hooks can be defined inside test.describe() to apply lifecycle operations to a particular group of tests.

12. What is the difference between hooks and fixtures?

Hooks define when lifecycle operations happen. Fixtures provide resources, manage dependencies, and control setup and teardown.

13. Can hooks be used for database cleanup?

Yes. Database utilities or cleanup APIs can be called from teardown hooks, provided the operations are properly implemented and isolated.

14. What is the difference between global setup and beforeAll()?

Global setup runs before the configured test run, while beforeAll() runs within a test scope in each applicable worker process.

15. Which hook is best for browser cleanup?

Use afterAll() to close manually created shared browser contexts. For standard test-scoped pages and contexts, Playwright fixtures handle cleanup automatically.

Leave a Comment

Your email address will not be published. Required fields are marked *