Playwright Tutorial: Re-use state & Re-use Authentication

Поделиться
HTML-код
  • Опубликовано: 11 сен 2024
  • Playwright provides a way to reuse the signed-in state in the tests. That way you can log in only once and then skip the log in step for all of the tests.
    Web apps use cookie-based or token-based authentication, where authenticated state is stored as cookies or in local storage. Playwright provides browserContext.storageState([options]) method that can be used to retrieve storage state from authenticated contexts and then create new contexts with pre-populated state.
    Cookies and local storage state can be used across different browsers. They depend on your application's authentication model: some apps might require both cookies and local storage.
    Code Generator video:
    • Playwright Test Genera...
    Code to use:
    await page.goto("demoblaze.com/");
    await page.locator("#login2").click();
    await page.locator("#loginusername").fill("test");
    await page.locator("#loginpassword").fill("test");
    await page.locator('[onclick="logIn()"]').click();
    await expect(page.locator("#logout2")).toBeVisible();

Комментарии • 83

  • @randolphcarter3906
    @randolphcarter3906 Год назад +4

    Ha ha! It took me a whopping twenty hours of experimenting with various approaches before I finally began to suspect that there might be an issue with the cookies I was attempting to capture. It turns out that the 'storageState' method was only saving an empty array because there were no cookies to store in the first place. It was quite a revelation when the developers informed me that we didn't even use cookies in our application. Talk about an unexpected twist!
    To address the issue, we decided to utilize the 'launchPersistentContext' method, which allowed us to persist the browser context across multiple tests. However, this introduced another challenge: there is no straightforward way to log out after the tests are completed. Automation certainly has its fair share of surprises!

    • @sexcommunist
      @sexcommunist Год назад

      Does this method only save cookies or your application doesn't save the token (or whatever is used for authentication in your case) in any kind of persistent storage?

  • @amitLeshem1
    @amitLeshem1 2 месяца назад

    Well done. That's exactly what I was looking for, and it covered all the questions I had.
    👍

  • @jessebanner1
    @jessebanner1 4 месяца назад

    Great video. I was able to follow along and my tests can now reuse the auth. Thank you!

  • @shilpashravge5393
    @shilpashravge5393 2 месяца назад

    Great explanation! Very useful ! Thanks !

  • @contaminantbean
    @contaminantbean Год назад +1

    Really great video, explained very clearly! 😃

  • @Bercilakdehautdesert-yt1gd
    @Bercilakdehautdesert-yt1gd 4 месяца назад

    Thank you, fab instructional - I was struggling with this.

  • @romainp.9984
    @romainp.9984 29 дней назад

    this solution is good, despite a few flaws, when we have multiple browser and login to use and cannot use the same login for different browser because only session are unique for each login ( meaning you cant connect on two different place, brower or computer with the same login at the same time ) , it's becoming kinda complicated. In my case I'm trying to figure how to get the project name in the global setup to make the login dynamic depending on which browser or device is used to generate a login! xD
    It also doesnt work with custom testIdAttributes, you're basically forced to put all your playwright config into the global config

    • @CommitQuality
      @CommitQuality  25 дней назад

      Why not use the project name for each login e.g. you could make the username a parameter of what browser it is using e.g. your global setup would be exact same setup I have here, but instead of the hardcoded username you could have one for ChromeUser, another for FirefoxUser etc.. I assume you would want to run your different browsers tests as different projects.

  • @asdfasdfq6005
    @asdfasdfq6005 11 месяцев назад +1

    Our page directly redirects to the MSAL login screen, is there an easy way to do this?

  • @MujahidMohd-cn7rb
    @MujahidMohd-cn7rb 29 дней назад +1

    what if we have to run the test on multiple browser , you are hardcoding the browser here in global setup

    • @CommitQuality
      @CommitQuality  25 дней назад

      Use multiple projects and change the browser per project. If you need to use different browsers in the same project you would have to setup a new browser and context

  • @theillo4739
    @theillo4739 6 месяцев назад

    You are great! Thanks for your content :)!

  • @yohannesdessie7206
    @yohannesdessie7206 6 месяцев назад

    Very well explained. Thank you

  • @fernando-kw
    @fernando-kw Год назад

    Thanks for video!! was very helpful

  • @danalex2991
    @danalex2991 9 месяцев назад

    Thanks. Helped a lot .

  • @adam-wc8uc
    @adam-wc8uc 5 месяцев назад +1

    how can I use signIn fixture in global setup?

  • @frols1
    @frols1 Год назад

    Hi. Thanks for a video. If i want to use two browsers Chrome and Firefox. Under the Firefox I need to create a separate global-setup ?

    • @CommitQuality
      @CommitQuality  Год назад +1

      Thank you :) no need for a new global setup, you can change your browser by creating a new project in the playwright config file. So you could have one project that runs your tests on chrome and another that runs your tests on Firefox. I have a video coming out soon on emulation and showing how you can change browsers, emulate devices and much more

  • @singh07neeraj
    @singh07neeraj 5 месяцев назад

    How to incease the session timeout as it is working for 4-5 test case after that Login screen started coming it means session is getting expired , I have more then 200 test case which run around 2 hours How to use it so that the session should not get expired

  • @dand4485
    @dand4485 Год назад

    Great explanation!!! 😎

  • @user-wz7om5un5c
    @user-wz7om5un5c 11 месяцев назад

    We store the auth token in Session Storage. Is there a way to save the Session Storage in storage-state?

  • @abdulwahabshariff894
    @abdulwahabshariff894 5 месяцев назад

    @Jared, When we use listeners like page.on vs Gobal setup, which takes priority? Also If we have multiple urls to store the storage state, and if we use a single global set up file within a single function to login to each url's and store the state files? Can you please share a code snippet on how we can handle multiple url's like stage, prod and store their state files seperately and use them seperately using global setup function? Please

    • @CommitQuality
      @CommitQuality  5 месяцев назад

      This video may help you with what you are looking for: ruclips.net/video/OpxLilD600I/видео.html

  • @07torne
    @07torne 2 месяца назад

    thank you!

  • @natbud7987
    @natbud7987 Год назад

    Thank you so much for the step-by-step explanation! The only thing that is not quite clear to me is the browser.close() at the end of the globalSetup. Don't we only want the login state to be persistent? I suppose if I omit that last line the test will open another window/tab?

    • @CommitQuality
      @CommitQuality  Год назад +1

      Yes we want to close off the browser. All the other tests run will have their own instance so it wouldn't impact the original step, it's just better practice to clean it up

  • @sivaramakrishnareddyrajula9605
    @sivaramakrishnareddyrajula9605 9 месяцев назад

    Hi, I tried to include loading ENV file and loggedstate.json in the same method, I am facing issue like TypeError: Cannot read properties of undefined (reading 'page').
    If we try to load env file using class constructor, getting below error.
    Error: utils\ui_globalSetup.ts: file must export a single function.
    Can you help to fix it?
    import dotenv from "dotenv";
    import { environment } from "./env";
    import { chromium } from "@playwright/test";
    import LoginPage from "../pages/Login.page";
    let loginPage: LoginPage;
    async function globalSetup() {
    if (process.env.test_env) {
    dotenv.config({
    path: `.env.${process.env.test_env}`,
    override: true
    })
    }
    const browser = await chromium.launch();
    const page = await browser.newPage();
    loginPage = new LoginPage(page);
    const baseURL = `${environment.UI_BASE_URL}`;
    const userName = `${environment.UI_USER_NAME}`;
    const password = `${environment.UI_PASSWORD}`;
    console.log(baseURL);
    console.log(userName);
    console.log(password);
    // Login
    await page.goto(baseURL);
    await loginPage.verifyTitle();
    await loginPage.enterUserName(userName);
    await loginPage.enterPassword(password);
    await loginPage.clickSignIn();
    await loginPage.enterSecurityAnswer();
    await loginPage.verifyBtn.click();
    // Save Signed-In State to loggedInState.json
    await page.context().storageState({ path: 'loggedInState.json' });
    await browser.close();
    }
    export default globalSetup;

    • @Topio1912
      @Topio1912 7 месяцев назад

      try non-null assertion: process.env.PASSWORD!

  • @buries_r
    @buries_r 4 месяца назад +1

    How to avoid creating storageState file in project ?

    • @CommitQuality
      @CommitQuality  4 месяца назад +2

      You won't be able to re-use the state of you don't have the file saved

    • @buries_r
      @buries_r 4 месяца назад +1

      @@CommitQuality ok. Added it to gitignore

  • @zaheer21
    @zaheer21 6 месяцев назад

    Is there any other way that is not dependent on cookies?

  • @olesnikaniuk6008
    @olesnikaniuk6008 Год назад

    Thanks for a video. We can pass an empty object directly in storageState as well for no authentication. Could you make a video for a multiple storageStates using new feature of dependency projects to have several global setups?

    • @CommitQuality
      @CommitQuality  Год назад

      Yes definitely. I have an action on my backlog to go over showing how we can do this using the new dependency functionality, hopefully will be recorded and out within a few weeks :) Thanks for the comment!

  • @adam-wc8uc
    @adam-wc8uc 5 месяцев назад

    what if my sigin is getting details after signup api call??

  • @hananurrehman
    @hananurrehman 8 месяцев назад

    How does this work with fixtures?
    So lets say you want to store login state but also want to use POM fixtures?

    • @CommitQuality
      @CommitQuality  7 месяцев назад

      Try this video: it used project dependencies which means setup is now treated as a test.
      ruclips.net/video/kFpI03tPLLM/видео.htmlsi=276Z_6NBs6l4loDa

  • @user-ki5lg2qq1l
    @user-ki5lg2qq1l 3 месяца назад

    What if we want to login with different credentials during login? How we will approach that

    • @CommitQuality
      @CommitQuality  3 месяца назад

      I have a video on using dotenv. That will be of use to you

  • @sumitjain7651
    @sumitjain7651 2 месяца назад

    Thanks for sharing this video. What if this cookie expired after some time, will that storage_state gonna work like this?

    • @CommitQuality
      @CommitQuality  Месяц назад

      You would need to re-run the login if it is expiring

  • @4CDMA
    @4CDMA 7 месяцев назад

    May be better use API request to login than use browser auth?

    • @CommitQuality
      @CommitQuality  7 месяцев назад

      Yes you can do that and it would speed up your tests (while also making them more stable). I'm some cases, you may want to test the login via the UI so it totally depends on your needs, however you're right that if you don't need to test the UI then definitely go via API calls

  • @planktonblooms
    @planktonblooms Год назад

    What are your thoughts of gherkin cucumber and playwright please? Are there any issues which i need to look out for please?

    • @CommitQuality
      @CommitQuality  Год назад +3

      This is a great question. I am a big fan of BDD, if done correctly in a company. I really see the benefits of using tools like cucumber to aid BDD, however many times I have seen BDD tools being used, but no real BDD process being implemented properly, which ends up leading to an overhead of maintaining gherkin (feature files) that no one reads.
      I have set up frameworks with cucumber and playwright and the main issue I found was I much prefer playwright test as the test runner, everything you get out of the box and the configuration was so much more beneficial to me than using the cucumber runner, I do plan on videos in the future with cucumber and playwright, however personally I now try to stick to using playwright test and only implement bdd tools if a client / project really want to work using BDD as a process

  • @moridwaqif
    @moridwaqif 7 месяцев назад

    Thank you for this tutorial. would you please show how to create Project Dependencies? playwright encourage to use dependencies than this approach. it says "Using globalSetup and globalTeardown will not produce traces or artifacts. If you want to produce traces and artifacts, use project dependencies."

    • @CommitQuality
      @CommitQuality  7 месяцев назад +1

      Great point, this videos was created before project dependencies were introduced. I have another video showing how you can use project dependencies ruclips.net/video/kFpI03tPLLM/видео.htmlsi=276Z_6NBs6l4loDa

    • @moridwaqif
      @moridwaqif 7 месяцев назад

      @@CommitQualityThank you for clear instruction.

  • @planktonblooms
    @planktonblooms Год назад

    Why do you use typescript instead of C#? Are there any advantages of using Typescript?

    • @CommitQuality
      @CommitQuality  Год назад

      A little sneak peak, I'm planning on creating playwright c# videos too!
      To answer your questions, playwright test (which you see me using with TS) is far more advanced than the .net bindings of playwright. Most of what you want comes straight out of the box and is very simple to adapt and use. The community support for playwright test is far better than the .bet version and you tend to get all the cooler things first with playwright test, for example the new UI watch mode.

  • @seangsengly-x1l
    @seangsengly-x1l Год назад

    How about I have many URL?
    Example: Test 1 -3 need using with URL : A
    and Test 4-6 need using with URL: B
    How we do ?

    • @CommitQuality
      @CommitQuality  Год назад +1

      You can use global setup to do multiple states and save them into different files for each state. You can then say for each group of tests which state file to use (similar to where we showed how to clear it, you can just point to the file you want to reference)

  • @Ashokkumar-uv4fs
    @Ashokkumar-uv4fs 7 месяцев назад +1

    Is it possible to use in azure pipeline?

    • @CommitQuality
      @CommitQuality  7 месяцев назад

      Yes it is

    • @Ashokkumar-uv4fs
      @Ashokkumar-uv4fs 7 месяцев назад

      @@CommitQuality is it possible to generate file while pipeline running and if expire how to generate again?

  • @PriyadharshiniElangovan-o4d
    @PriyadharshiniElangovan-o4d Месяц назад

    audio can be little better ... video content is
    awesome

    • @CommitQuality
      @CommitQuality  Месяц назад

      I believe this video was recorded on an older microphone. The audio in my more recent videos should be much better

  • @bokkie2650
    @bokkie2650 Год назад

    how can this be handled in case of tokens that expire every whatever minutes?

    • @CommitQuality
      @CommitQuality  Год назад

      You would likely want to do it before the tests if you have a very small timeframe on the expiry. Using hooks or fixtutrs

  • @AsimKhan326
    @AsimKhan326 Год назад

    is there the same example available in python ?

    • @CommitQuality
      @CommitQuality  Год назад

      Yes there is, I dont have a video uploaded for this, but its very similar to this vide - Heres the official documentation: playwright.dev/python/docs/auth

  • @3vilass
    @3vilass Год назад

    Google Firebase uses indexedDB instead of Cookies or SessionStorage. StorageState does not persist the indexedDB here. Maybe you know a solution for this? :-)

    • @benjaminiriberri7737
      @benjaminiriberri7737 Год назад

      could you solve it? I guess I have the same problem, since the video does not work for me

    • @3vilass
      @3vilass Год назад

      @@benjaminiriberri7737 Sorry, stop trying and stay with the old way to fill the forms.

  • @nxone9903
    @nxone9903 6 месяцев назад

    can i make it work by setting cookies in a beforeEach?

    • @CommitQuality
      @CommitQuality  5 месяцев назад

      Yes the code will work anywhere

  • @bogdanbeniw3493
    @bogdanbeniw3493 3 месяца назад

    U r amazing. Thank you for this video. like/subscription

  • @sionheaney2744
    @sionheaney2744 4 месяца назад

    Much appreciated. Ta

  • @ghostinlinux3270
    @ghostinlinux3270 8 месяцев назад

    Can we access loginauth when we use playwright ui mode??

    • @CommitQuality
      @CommitQuality  8 месяцев назад

      Yes you can

    • @ghostinlinux3270
      @ghostinlinux3270 8 месяцев назад

      @@CommitQuality but in my case tests folder and storage state folder present in root directory and when i open ui mode and run the test file. It give me the error that cannot read the file storage state. In storage state folder i stored my json file

  • @user-hm5eo1qj5t
    @user-hm5eo1qj5t 6 месяцев назад

    Good video, good explaining but very low voice volume.

    • @CommitQuality
      @CommitQuality  6 месяцев назад +1

      Thank you. Apologies for the audio, I had a poor setup at the time. Future videos should have much better quality audio

  • @leebobtheblob87
    @leebobtheblob87 7 месяцев назад

    13:47 code generator method