[Fixed] Playwright – receiving error 'locator.click: Target page, context or browser has been closed' between test run – Playwright

by
Ali Hasan
playwright playwright-test

Quick Fix: Declare a beforeEach hook that is executed before each test. Avoid opening and closing the browser within individual tests.

The Problem:

In Playwright, when running multiple tests together, tests that run after a successful test fail with errors like ‘Target page, context or browser has been closed.’ The issue occurs specifically with actions like ‘setInputFiles’ and ‘locator.click,’ and it appears to be related to the use of a ‘userFixture.ts’ file.

The Solutions:

Solution 1: Declare test.beforeEach hook.

In the provided code, the browser is being opened once and closed after each test. To fix this issue, you should use the `test.beforeEach` hook to open the browser before each test and the `test.afterEach` hook to close the browser after each test. Here’s an example of how to use these hooks:

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

test.beforeEach(async ({ browser }) => {
  // Open the browser before each test
  await browser.newContext();
});

test.afterEach(async ({ browser }) => {
  // Close the browser after each test
  await browser.close();
});

test('my test', async ({ page }) => {
  // Your test code goes here
  expect(page.url()).toBe('https://my.start.url/');
});

Q&A

What is the issue?

You are opening browser once and trying to close after each test

How can I fix this issue?

Use beforeEach instead of beforeAll

Video Explanation:

The following video, titled "How to Fix Playwright Install Error when using Auto-py-to-exe ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Learn how to fix a common error when using the #playwright library in your #Python script with #pyinstaller or #autopytoexe to create an ...