Rayrun

How do I use fixtures in Playwright Test to set up and tear down test environments?

Answer

Sure, let's dive into how you can use fixtures in @playwright/test to set up your test environment.

First, define your account type with a username and password:

type Account = {
  username: string;
  password: string;
};

Next, extend the base test fixture from Playwright Test to include your custom account fixture:

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

export const test = base.extend<{}, { account: Account }>({
  account: [async ({ browser }, use, workerInfo) => {
    const username = 'user' + workerInfo.workerIndex;
    const password = 'verysecure';
    
    const newUser = await createUserAccount(browser, username, password);
    
    await use(newUser);
    
    await deleteUserAccount(browser, newUser.id);
  }],
});

In this code:

  • We're extending the test fixture with our account fixture.
  • We're passing an async function to set up our account fixture.
  • We're generating a unique username based on the worker index.
  • We're creating a new user account with a hypothetical function createUserAccount.
  • We're passing the newly created user object along.
  • We're cleaning up with a hypothetical function deleteUserAccount.

This is a basic example of how you can use fixtures to set up and tear down your test environment in @playwright/test. For more advanced usage, check out Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet.

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 luc@ray.run.