One of the better practices that Playwright’s library supports out of the box ,is pre-authenticated “set-up” state for tests.
How do we securely and efficiently pass browser session state between tests without having to write code in every test to recreate & demolish that state ?
- Create separate tests for set up
- Pass on the browser state from set up test to subsequent tests & make those tests dependent on the set up tests
- Segregate tests that do not require that browser state
How can Playwright help :
I’m sure there are multiple ways to design this, but the approach that I learnt from my tinkering is as below ( a Node.js and Typescript example)
- Create (reusable) setup test file– The concept of Project dependencies allows sequencing of tests that depend on other tests
a) declare a test to be a set up test
b) write steps to create the browser state that you want . Below is a simple example of going to an commerce site and logging in by entering credentials on a login page
(Security note – Remember to git ignore any auth related files & folders , plus use CI secrets or environment variables)
2. State storage in set up test file – Enable the set up test to capture browser state information post login
a) In the setup test …
b) Store the state…
3. Enable Sequencing in Playwright config file– Declare dependencies in tests & pass browser user state to subsequent tests
This is controlled by the playwright.config file using projects and Playwright authentication file
(Security note, again – Remember to git ignore any auth related files & folders , plus use CI secrets or environment variables)
From here on, any tests that you write matching the expression below
,will have a dependency on the ‘setup’ project i.e. will automatically call the setup test first and will use the browser state
This is how my playwright.config file looks like –
and this is how my common set up test file looks like –
hence, any subsequent tests i write , are oblivious to authenticating/recreating the browser state .
And to test this premise, I just wrote a test to make sure that I am already logged when when the home page of the e-commerce site is called to ensure that the Playwright project dependency feature actually works 😉
Side tip –
If you haven’t, the VSCode Playwright plugin is a must try –> https://playwright.dev/docs/getting-started-vscode
Makes working with Playwright project so much efficient !
Leave a Reply