Practical Example: Login Fixture in Playwright

Now let’s look at a practical example.

Imagine you are testing an application where several test cases require a logged-in user.

Instead of repeating the login steps in every test, you can create a custom fixture that logs in the user and provides the authenticated page.

Create a file named fixtures.ts:

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

type MyFixtures = {
  loggedInPage: import('@playwright/test').Page;
};

export const test = base.extend<MyFixtures>({
  loggedInPage: async ({ page }, use) => {
    await page.goto('https://your-app.example/login');

    await page.getByLabel('Username').fill('testuser');
    await page.getByLabel('Password').fill('password123');
    await page.getByRole('button', { name: 'Login' }).click();

    await expect(page).toHaveURL(/dashboard/);

    await use(page);
  },
});

export { expect };

Now use the fixture in your test:

import { test, expect } from './fixtures';

test('Verify dashboard is visible', async ({ loggedInPage }) => {
  await expect(
    loggedInPage.getByRole('heading', { name: 'Dashboard' })
  ).toBeVisible();
});

How does this example work?

  1. Playwright provides the built-in page fixture.
  2. The custom fixture opens the login page.
  3. It enters the test username and password.
  4. It clicks the Login button.
  5. It checks that the application navigates to the dashboard.
  6. It provides the authenticated page to the test through use(page).
  7. After the test finishes, Playwright completes the fixture lifecycle and cleans up the page.

Replace the example URL, labels, credentials, and dashboard heading with the actual details of your application. Use dedicated test credentials rather than real user passwords.

This approach is useful when several tests need the same login setup.

However, if the application has a reliable authentication API or supports saved authentication state, you may be able to make login setup faster by reusing authenticated state.

Pages: 1 2 3 4 5 6

Leave a Reply

Your email address will not be published. Required fields are marked *