Playwright with TypeScript | Save and Reuse Authentication state:
The playwright executes tests in isolated environments called browser contexts. By reusing authentication state, tests can load existing authenticated states. This eliminates the need to authenticate in every test and speeds up test execution.
Here we will authenticate once in the setup project, save the authentication state, and then reuse it to bootstrap each test already authenticated.
We will create a new setup project in the config file and declare it as a dependency for all your testing projects. This project will always run and authenticate before all the tests. All testing projects should use the authenticated state as storageState.
Reusing authenticated state covers cookies and all storage-based authentication.
Cookies - An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser. The browser may store the cookie and send it back to the same server with later requests. Typically, an HTTP cookie is used to tell if two requests come from the same browser-keeping a user logged in.
Below are 3 different ways to save/preserve and reuse the Authentication state:
1- By using the Codegen command - Run codegen with -save-storage to save cookies and localStorage at the end of the session. This is useful to separately record an authentication step and reuse it later when recording more tests.
2- By using globalSetup - We can use the globalSetup option in the configuration file to set something up once before running all tests. Here, it will authenticate once and reuse the authentication state in tests.
3- By using Dependencies - Project dependencies are a list of projects that need to run before the tests in another project run. With project dependencies, you define a project that runs before all other projects. This is the recommended way to configure global setup as with Project dependencies, your HTML report will show the global setup, the trace viewer will record a trace of the setup, and fixtures can be used.
Avoid authentication in some test cases: we can reset the storage in a test file to avoid authentication that was set up for the whole project. test.use({storageState:{cookies:[], origins:[]} })