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

  Рет қаралды 29,984

CommitQuality

CommitQuality

Жыл бұрын

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();

Пікірлер: 79
@jessebanner1
@jessebanner1 2 ай бұрын
Great video. I was able to follow along and my tests can now reuse the auth. Thank you!
@contaminantbean
@contaminantbean Жыл бұрын
Really great video, explained very clearly! 😃
@randolphcarter3906
@randolphcarter3906 Жыл бұрын
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 11 ай бұрын
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?
@shilpashravge5393
@shilpashravge5393 18 күн бұрын
Great explanation! Very useful ! Thanks !
@fernando-kw
@fernando-kw Жыл бұрын
Thanks for video!! was very helpful
@amitLeshem1
@amitLeshem1 Ай бұрын
Well done. That's exactly what I was looking for, and it covered all the questions I had. 👍
@CommitQuality
@CommitQuality Ай бұрын
Glad it helped
@danalex2991
@danalex2991 8 ай бұрын
Thanks. Helped a lot .
@yohannesdessie7206
@yohannesdessie7206 4 ай бұрын
Very well explained. Thank you
@CommitQuality
@CommitQuality 4 ай бұрын
Glad it was helpful! Thanks
@dand4485
@dand4485 Жыл бұрын
Great explanation!!! 😎
@CommitQuality
@CommitQuality Жыл бұрын
Thank you :)
@Bercilakdehautdesert-yt1gd
@Bercilakdehautdesert-yt1gd 2 ай бұрын
Thank you, fab instructional - I was struggling with this.
@CommitQuality
@CommitQuality 2 ай бұрын
You're welcome!
@theillo4739
@theillo4739 4 ай бұрын
You are great! Thanks for your content :)!
@CommitQuality
@CommitQuality 4 ай бұрын
I appreciate that! Thank you
@07torne
@07torne 18 күн бұрын
thank you!
@asdfasdfq6005
@asdfasdfq6005 9 ай бұрын
Our page directly redirects to the MSAL login screen, is there an easy way to do this?
@natbud7987
@natbud7987 11 ай бұрын
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 10 ай бұрын
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
@user-wz7om5un5c
@user-wz7om5un5c 9 ай бұрын
We store the auth token in Session Storage. Is there a way to save the Session Storage in storage-state?
@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 4 ай бұрын
how can I use signIn fixture in global setup?
@frols1
@frols1 11 ай бұрын
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 11 ай бұрын
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
@adam-wc8uc
@adam-wc8uc 4 ай бұрын
what if my sigin is getting details after signup api call??
@zaheer21
@zaheer21 5 ай бұрын
Is there any other way that is not dependent on cookies?
@singh07neeraj
@singh07neeraj 3 ай бұрын
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
@abdulwahabshariff894
@abdulwahabshariff894 4 ай бұрын
@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 4 ай бұрын
This video may help you with what you are looking for: kzbin.info/www/bejne/haHbfZyieZtjZqs
@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 Жыл бұрын
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
@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.
@moridwaqif
@moridwaqif 6 ай бұрын
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 6 ай бұрын
Great point, this videos was created before project dependencies were introduced. I have another video showing how you can use project dependencies kzbin.info/www/bejne/oXfTemNpqbV_gq8si=276Z_6NBs6l4loDa
@moridwaqif
@moridwaqif 6 ай бұрын
@@CommitQualityThank you for clear instruction.
@user-pj7hu6he5j
@user-pj7hu6he5j Жыл бұрын
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 11 ай бұрын
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)
@4CDMA
@4CDMA 5 ай бұрын
May be better use API request to login than use browser auth?
@CommitQuality
@CommitQuality 5 ай бұрын
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
@hananurrehman
@hananurrehman 6 ай бұрын
How does this work with fixtures? So lets say you want to store login state but also want to use POM fixtures?
@CommitQuality
@CommitQuality 6 ай бұрын
Try this video: it used project dependencies which means setup is now treated as a test. kzbin.info/www/bejne/oXfTemNpqbV_gq8si=276Z_6NBs6l4loDa
@sumitjain7651
@sumitjain7651 18 күн бұрын
Thanks for sharing this video. What if this cookie expired after some time, will that storage_state gonna work like this?
@CommitQuality
@CommitQuality 5 күн бұрын
You would need to re-run the login if it is expiring
@sionheaney2744
@sionheaney2744 3 ай бұрын
Much appreciated. Ta
@sivaramakrishnareddyrajula9605
@sivaramakrishnareddyrajula9605 7 ай бұрын
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 6 ай бұрын
try non-null assertion: process.env.PASSWORD!
@bokkie2650
@bokkie2650 11 ай бұрын
how can this be handled in case of tokens that expire every whatever minutes?
@CommitQuality
@CommitQuality 10 ай бұрын
You would likely want to do it before the tests if you have a very small timeframe on the expiry. Using hooks or fixtutrs
@user-ki5lg2qq1l
@user-ki5lg2qq1l Ай бұрын
What if we want to login with different credentials during login? How we will approach that
@CommitQuality
@CommitQuality Ай бұрын
I have a video on using dotenv. That will be of use to you
@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
@nxone9903
@nxone9903 4 ай бұрын
can i make it work by setting cookies in a beforeEach?
@CommitQuality
@CommitQuality 4 ай бұрын
Yes the code will work anywhere
@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 10 ай бұрын
could you solve it? I guess I have the same problem, since the video does not work for me
@3vilass
@3vilass 10 ай бұрын
@@benjaminiriberri7737 Sorry, stop trying and stay with the old way to fill the forms.
@bogdanbeniw3493
@bogdanbeniw3493 Ай бұрын
U r amazing. Thank you for this video. like/subscription
@CommitQuality
@CommitQuality Ай бұрын
Thank you :)
@ghostinlinux3270
@ghostinlinux3270 6 ай бұрын
Can we access loginauth when we use playwright ui mode??
@CommitQuality
@CommitQuality 6 ай бұрын
Yes you can
@ghostinlinux3270
@ghostinlinux3270 6 ай бұрын
@@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
@buries_r
@buries_r 2 ай бұрын
How to avoid creating storageState file in project ?
@CommitQuality
@CommitQuality 2 ай бұрын
You won't be able to re-use the state of you don't have the file saved
@buries_r
@buries_r 2 ай бұрын
@@CommitQuality ok. Added it to gitignore
@Ashokkumar-uv4fs
@Ashokkumar-uv4fs 6 ай бұрын
Is it possible to use in azure pipeline?
@CommitQuality
@CommitQuality 6 ай бұрын
Yes it is
@Ashokkumar-uv4fs
@Ashokkumar-uv4fs 6 ай бұрын
@@CommitQuality is it possible to generate file while pipeline running and if expire how to generate again?
@PriyadharshiniElangovan-o4d
@PriyadharshiniElangovan-o4d 4 күн бұрын
audio can be little better ... video content is awesome
@CommitQuality
@CommitQuality 4 күн бұрын
I believe this video was recorded on an older microphone. The audio in my more recent videos should be much better
@user-hm5eo1qj5t
@user-hm5eo1qj5t 4 ай бұрын
Good video, good explaining but very low voice volume.
@CommitQuality
@CommitQuality 4 ай бұрын
Thank you. Apologies for the audio, I had a poor setup at the time. Future videos should have much better quality audio
@leebobtheblob87
@leebobtheblob87 5 ай бұрын
13:47 code generator method
Playwright Traceviewer Made Easy!
18:10
CommitQuality
Рет қаралды 2,3 М.
Summer shower by Secret Vlog
00:17
Secret Vlog
Рет қаралды 9 МЛН
Fast and Furious: New Zealand 🚗
00:29
How Ridiculous
Рет қаралды 12 МЛН
Пранк пошел не по плану…🥲
00:59
Саша Квашеная
Рет қаралды 6 МЛН
Setup & Re-Use Authentication with Playwright Dependencies!
11:03
CommitQuality
Рет қаралды 11 М.
Reuse Playwright  Code across Files and Tests with Fixtures
5:54
Performance Testing using Playwright
1:05:47
NY Web Performance Meetup
Рет қаралды 18 М.
When RESTful architecture isn't enough...
21:02
Dreams of Code
Рет қаралды 256 М.
Mastering Playwright | Skip Login using Storage State | QA Automation Alchemist
8:47
Mastering API Testing & Playwright: Expert Tips Revealed!
46:40
Automation Testing with Joe Colantonio
Рет қаралды 1,2 М.
Playwright Authentication: Shared Account in All Tests
16:34
JoanMedia
Рет қаралды 1,4 М.
Summer shower by Secret Vlog
00:17
Secret Vlog
Рет қаралды 9 МЛН