To ensure your authentication file is loaded for every test in Playwright, you'll need to create a setup project in your Playwright configuration file (playwright.config.ts
). This project will handle authentication before all tests.
First, define a test file (auth.setup.ts
) in your setup project. This file will prepare the authenticated browser state for all other tests.
// auth.setup.ts
import { setup } from '@playwright/test';
setup(async ({ page }) => {
await page.goto('https://ray.run/login');
await page.getByLabel('Username or email address').fill('username');
await page.getByLabel('Password').fill('password');
await page.getByRole('button', { name: 'Sign in' }).click();
await page.waitForURL('https://ray.run/');
});
After authentication, save the authenticated state as storageState
using page.context().storageState({ path: authFile })
. This saves the browser's storage state into a JSON file specified by authFile
.
// auth.setup.ts
import { setup } from '@playwright/test';
setup(async ({ page }) => {
// ...authentication steps...
await page.context().storageState({ path: 'playwright/.auth/user.json' });
});
In your testing projects (e.g., "chromium"
), specify 'playwright/.auth/user.json'
as the value for 'storageState'
. This ensures each testing project uses the authenticated state when running tests.
// playwright.config.ts
import { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
projects: [
{
name: 'chromium',
use: {
storageState: 'playwright/.auth/user.json',
},
},
// ...other projects...
],
};
export default config;
By following these steps, your authentication file will be loaded every time a test runs in Playwright.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].