Playwright BeforeAll and AfterAll Hooks

Profile picture for user arilio666

This article will discuss the afterAll and beforeAll hooks in playwright.


  • The beforeAll hook is executed before any tests in the suite are run and is typically used for setting up any global fixtures or dependencies that multiple tests will use. 
  • If you need to set up a database connection, you can do so in the beforeAll hook so that all tests in the suite can use it.
test.beforeAll(async () => {
   //can be used to initiate a browser instance.


  • The afterAll hook is executed after all tests in the suite have been completed and is typically used for tearing down any global fixtures or dependencies set up in the beforeAll hook.
test.afterAll(async () => {
   //close the browser instance.


For example purposes, we will use the programsbuzz site to enter the username and pass.

const {test, expect} = require('@playwright/test');
test.beforeAll(async ({browser}) => {
  const context = await browser.newContext()
  const page = await context.newPage()
 test.afterAll(async ({browser}) => {
   await browser.close()
test('User Login', async ({page})=> 
   await  page.goto('')
await page.locator('#edit-name').type('Naruto')
await page.locator('#edit-pass').type('Uzumaki')

  • Here we can see we created context and a new page before all this will create those before everything.
  • Then in, after all we declared that the browser context was to be closed.
  • This will run the test and close the browser instance when it is done after all the things are done.