Friday, May 9, 2025

Understanding storage state example in playwright

In this example we will explore how to implement storage state in playwright with example. storage state refers to saving and loading the browser's authentication state, such as cookies and localStorage. This allows you to persist a logged-in session and reuse it in future tests without logging in every time. It’s especially useful for speeding up tests and avoiding repeated UI interactions for login.

Understanding storage state example in playwright

When you call storageState, Playwright will make all the current cookie and localStorage entries accessible to you. If you will, storageState returns an entire browser storage session dump. 

You can either access all the data directly in JavaScript/TypeScript or write it directly to disk by defining a path option.

// return storage and session data
await page.context().storageState()
// write storage and session data to disk
await page.context().storageState({ path: ".auth/user.json" })

Using Storage State in Playwright

Let's go through an example step-by-step to storage session in 01-login.spec.js spec file and access the session in another spec file that is  02-auth_check.spec.js.


01-login.spec.js

Create a script to log in and save the state to a file by using.

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

test('login to sauce account', async ({ browser }) => {

    const context = await browser.newContext();
    const page = await context.newPage();

    await page.goto('https://demos.9lessons.info/login.php');
    await page.locator('input[name="username"]').click();
    await page.locator('input[name="username"]').fill('test');
    await page.locator('input[name="password"]').click();
    await page.locator('input[name="password"]').fill('test');
    await page.getByRole('button', { name: 'Submit' }).click();

    // Wait for navigation or some indication of login success
    await page.waitForURL('**/welcome.php');

    //check with assertion
    await expect(page.locator('h1')).toContainText('Welcome test'); 
    
    // Save the authenticated state to a file
    await context.storageState({ path: 'auth.json' });
});


02-auth_check.spec.js

Now, load the saved storage state in your tests:

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

test.use({ storageState: 'auth.json' });

test('should access dashboard as logged-in user', async ({ browser }) => {
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://demos.9lessons.info/welcome.php');
  await expect(page.locator('h1')).toContainText('Welcome test'); 

  // Get current storage state
  const state = await context.storageState();
  console.log(JSON.stringify(state, null, 2));
 
});


Use below command to run the playwright script :

npx playwright test 01-login.spec.js 02-auth_check.spec.js --project=chromium --workers=1

Running 2 tests using 1 worker

    1 [chromium]  tests\storageState-example\01-login.spec.js:3:5  login to sauce account (13.1s)
  2 [chromium]  tests\storageState-example\02-auth_check.spec.js:5:5  should access dashboard as logged-in user


If you inspect the returned storage state, you'll find a nicely structured object that gives you cookie and localStorage entries. For that look into auth.json file


Additionally, if you want to handle storage state using config,  then follow the following steps.

playwright.config.js

import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    storageState: 'storageState.json',
  },
});


This is all about handling session using storage state in playwright.


No comments:

Post a Comment