Rayrun

How do I set up and use multiple user roles in Playwright tests with Sauce Labs?

Answer

Setting Up Login Fixtures with Multiple User Roles

To save the state of multiple users in Sauce Labs and Playwright, follow these steps:

  1. Authenticate as a user: Perform authentication steps like filling in username and password fields, and clicking the sign-in button. Replace these actions with your custom actions. Wait until the page receives cookies or reaches a state with all cookies set.
import { test, expect } from '@playwright/test';

test('authenticate as a user', async ({ page }) => {
  await page.goto('https://ray.run/login');
  await page.fill('#username', 'your-username');
  await page.fill('#password', 'your-password');
  await page.click('#sign-in');
  await page.waitForSelector('#logged-in');
});
  1. Specify storageState for each test file or test group: Instead of setting it in the config, this allows you to authenticate as different users for different tests.
import { test, expect } from '@playwright/test';

test.use({ storageState: 'path/to/admin-storage-state.json' });

test('admin test', async ({ page }) => {
  // Your admin test code here
});

test.use({ storageState: 'path/to/user-storage-state.json' });

test('user test', async ({ page }) => {
  // Your user test code here
});

Testing Multiple Authenticated Roles

For testing how multiple authenticated roles interact together in a single test, you can:

  • Use multiple BrowserContexts and Pages: Create one context/page pair signed in as "admin" and another context/page pair signed in as "user". Interact with both pages within your single test.

  • Introduce fixtures: Create fixtures that provide a page authenticated as each role. For example, create fixtures for both admin and user pages that provide them already signed-in with their respective accounts.

Reusing Accounts Across Tests

If you want to reuse accounts across all tests, authenticate multiple times in the setup project using worker-scoped fixture. This ensures unique authentication state per worker process while running parallel tests on Sauce Labs cloud platform.

Thank you!
Was this helpful?
Still have questions?

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

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