Rayrun

How do I use different user credentials or tokens for each spec file in an API project with Playwright?

Answer

To use different user credentials or tokens for each spec file in an API project with Playwright, you can create a helper function that handles the authentication process. This function can be imported and used in each spec file to set up the required user context.

Here's a step-by-step guide:

1. Create a helper function for authentication

Create a authHelper.ts file and define a function authenticateUser that takes the user credentials or token as a parameter and returns the authenticated user context.

// authHelper.ts
import { test } from '@playwright/test';

export async function authenticateUser(userCredentials: { email: string; password: string }) {
  const response = await test.fetch('https://ray.run/api/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userCredentials),
  });

  const data = await response.json();
  return data;
}

2. Use the helper function in spec files

In each spec file, import the authenticateUser function and use it to authenticate the user before running the tests.

// example.spec.ts
import { test } from '@playwright/test';
import { authenticateUser } from './authHelper';

test.beforeEach(async ({ context }) => {
  const userCredentials = { email: '[email protected]', password: 'password' };
  const userData = await authenticateUser(userCredentials);

  // Set the authenticated user context
  context.extend({ userData });
});

test('example test', async ({ page, context }) => {
  const { userData } = context;
  // Use userData.token or other user data in your tests
});

By following these steps, you can easily set up different user credentials or tokens for each spec file in your API project using Playwright.

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