Rayrun

What are some best practices for writing a Playwright test for a login form?

Answer

Writing a Playwright Test for a Login Form

When writing a Playwright test for a login form, focus on testing user-visible behavior. Avoid relying on function names or CSS classes. Instead, verify what is rendered on the page and interact with those elements.

Each test should be independent, running with its own local storage, session storage, data, cookies, etc. This improves reproducibility and makes debugging easier. You can use before hooks to avoid repetition in your tests. For example, going to a particular URL or logging in to a part of your app.

Use Playwright's built-in locators to find elements on the webpage. These come with auto waiting and retry-ability features, ensuring that Playwright performs actionability checks on elements before performing any clicks.

When testing authentication steps like logging in, perform these steps in setup functions instead of within individual tests. This avoids repeated code across multiple files or groups of files. You can specify storageState for each test file or group instead of setting it in the config.

Here's a TypeScript example:

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

test.beforeEach(async ({ page }) => {
  await page.goto('https://ray.run/login');
});

test('login form', async ({ page }) => {
  await page.fill('input[name="username"]', 'user');
  await page.fill('input[name="password"]', 'pass');
  await page.click('button[type="submit"]');
  expect(await page.url()).toBe('https://ray.run/dashboard');
});

For more tips on writing efficient Playwright test scripts, check out this blog post.

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