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();
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!
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?
Well done. That's exactly what I was looking for, and it covered all the questions I had.
👍
Glad it helped
Great video. I was able to follow along and my tests can now reuse the auth. Thank you!
Great explanation! Very useful ! Thanks !
Really great video, explained very clearly! 😃
Thank you, fab instructional - I was struggling with this.
You're welcome!
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
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.
Our page directly redirects to the MSAL login screen, is there an easy way to do this?
what if we have to run the test on multiple browser , you are hardcoding the browser here in global setup
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
You are great! Thanks for your content :)!
I appreciate that! Thank you
Very well explained. Thank you
Glad it was helpful! Thanks
Thanks for video!! was very helpful
Thanks. Helped a lot .
how can I use signIn fixture in global setup?
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 ?
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
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
Great explanation!!! 😎
Thank you :)
We store the auth token in Session Storage. Is there a way to save the Session Storage in storage-state?
@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
This video may help you with what you are looking for: ruclips.net/video/OpxLilD600I/видео.html
thank you!
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?
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
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;
try non-null assertion: process.env.PASSWORD!
How to avoid creating storageState file in project ?
You won't be able to re-use the state of you don't have the file saved
@@CommitQuality ok. Added it to gitignore
Is there any other way that is not dependent on cookies?
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?
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!
what if my sigin is getting details after signup api call??
How does this work with fixtures?
So lets say you want to store login state but also want to use POM fixtures?
Try this video: it used project dependencies which means setup is now treated as a test.
ruclips.net/video/kFpI03tPLLM/видео.htmlsi=276Z_6NBs6l4loDa
What if we want to login with different credentials during login? How we will approach that
I have a video on using dotenv. That will be of use to you
Thanks for sharing this video. What if this cookie expired after some time, will that storage_state gonna work like this?
You would need to re-run the login if it is expiring
May be better use API request to login than use browser auth?
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
What are your thoughts of gherkin cucumber and playwright please? Are there any issues which i need to look out for please?
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
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."
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
@@CommitQualityThank you for clear instruction.
Why do you use typescript instead of C#? Are there any advantages of using Typescript?
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.
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 ?
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)
Is it possible to use in azure pipeline?
Yes it is
@@CommitQuality is it possible to generate file while pipeline running and if expire how to generate again?
audio can be little better ... video content is
awesome
I believe this video was recorded on an older microphone. The audio in my more recent videos should be much better
how can this be handled in case of tokens that expire every whatever minutes?
You would likely want to do it before the tests if you have a very small timeframe on the expiry. Using hooks or fixtutrs
is there the same example available in python ?
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
Google Firebase uses indexedDB instead of Cookies or SessionStorage. StorageState does not persist the indexedDB here. Maybe you know a solution for this? :-)
could you solve it? I guess I have the same problem, since the video does not work for me
@@benjaminiriberri7737 Sorry, stop trying and stay with the old way to fill the forms.
can i make it work by setting cookies in a beforeEach?
Yes the code will work anywhere
U r amazing. Thank you for this video. like/subscription
Thank you :)
Much appreciated. Ta
Can we access loginauth when we use playwright ui mode??
Yes you can
@@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
Good video, good explaining but very low voice volume.
Thank you. Apologies for the audio, I had a poor setup at the time. Future videos should have much better quality audio
13:47 code generator method