Reusing Signed in State in Playwright

Profile picture for user arilio666

In playwright JS, we can reuse signed in the state in a test. This will help us by logging in only once and skipping the login process for all the tests next time.

Today we will see how we can do that using playwright JS.

Understanding Web Apps:

  • Typically web apps use cookie-based or even token-based types of authentication where they are stored as cookies or in local storage.
  • With playwright, it provides context.storageState([options]) method can fetch the storage state from the authentication context.
  • This will create new contexts with a preoccupied state.

Example:

For this, we will be using this demo login site called https://practicetestautomation.com/practice-test-login/

const browser = await chromium.launch()
const context = await browser.newContext()
const page = await context.newPage()

await page.goto('https://practicetestautomation.com/practice-test-login/');
await page.locator("input[id='username']").type('student')
await page.locator("input[id='password']").type('Password123') 
await page.locator("button[id='submit']").click()

const loginText = await page.locator("//strong[contains(text(),'Congratulations student. You successfully logged i')]").textContent()      

console.log(loginText)

await context.storageState({path: 'auth.json'})
  • First, we run it as usual with a storage state set with JSON as the file to be saved the login info.
  • We can see the login state has been saved here for this site. Let us see how we can reuse it.
const browser = await chromium.launch()
const context = await browser.newContext({storageState: 'auth.json'})
const page = await context.newPage()
       
await page.goto('https://practicetestautomation.com/practice-test-login/');

const loginText = await page.locator("//strong[contains(text(),'Congratulations student. You successfully logged i')]").textContent()      

console.log(loginText)
  • Now using the context, we create a new context option and set the storage state path of the JSON file we created.
  • This way, we don't need to enter login credentials again.