Reusing Signed in State in Playwright Java

Profile picture for user arilio666

In playwright java, 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 java.

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 browserContext.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/

  Playwright playwright = Playwright.create();
        BrowserContext browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false))
                .newContext();
        
        Page page = browser.newPage();

        page.navigate("https://practicetestautomation.com/practice-test-login/");

        page.locator("//input[@id='username']").type("student");
        page.locator("//input[@id='password']").type("Password123");

        page.locator("//button[@id='submit']").click();
        String textContent = page
                .locator("//strong[contains(text(),'Congratulations student. You successfully logged i')]")
                .textContent();
        System.out.println(textContent);

         browser.storageState(new BrowserContext.StorageStateOptions().setPath(Paths.get("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.

   Playwright playwright = Playwright.create();
        BrowserContext browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false))
                .newContext(new Browser.NewContextOptions().setStorageStatePath(Paths.get("auth.json")));
    
        Page page = browser.newPage();

        page.navigate("https://practicetestautomation.com/practice-test-login/");


        String textContent = page
                .locator("//strong[contains(text(),'Congratulations student. You successfully logged i')]")
                .textContent();
        System.out.println(textContent);     

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.