Rayrun

How do I implement a shared login session across multiple tests in @playwright/test?

Answer

Sure, let's get you set up with a shared login session for your @playwright/test tests.

First, you'll need to create an auth.setup.ts file. This file will handle the authentication and save the state for all your tests.

Here's a basic example of what that might look like:

import { test, expect } from '@playwright/test';

test('login', async ({ page }) => {
  await page.goto('https://ray.run/login');
  await page.fill('input[name="username"]', 'your-username');
  await page.fill('input[name="password"]', 'your-password');
  await page.click('button[type="submit"]');
  const storage = await context.storageState();
  fs.writeFileSync('playwright/.auth/state.json', JSON.stringify(storage));
});

In this code, we're using Playwright's page object model to fill in the login form and click the submit button. We then save the authentication state to a JSON file.

Next, in each test file or group where you want to use this shared account, set the storageState property with the path to the JSON file.

import { test, expect } from '@playwright/test';
import * as fs from 'fs';

test.use({
  storageState: JSON.parse(fs.readFileSync('playwright/.auth/state.json', 'utf8')),
});

test('authenticated test', async ({ page }) => {
  // your test code here
});

This way, each test starts with an authenticated session, saving you the time of logging in for each test.

Remember, if your tests modify server-side state or if your authentication is browser-specific, using shared accounts may not be appropriate. In such cases, use multiple BrowserContexts and Pages with different storage states in the same test.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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].