Home > front end >  Is it possible to create custom commands in Playwright?
Is it possible to create custom commands in Playwright?

Time:11-16

I'm looking for a way to write custom commands in Playwright like it's done in Cypress. Playwright Issues has one page related to it but I have never seen any code example.

I'm working on one test case where I'm trying to improve code reusability. Here's the code:

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

config();

let context;
let page;

test.beforeEach(async () => {
  context = await chromium.launchPersistentContext(
    'C:\\Users\\User\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default',
    {
      headless: false,
      executablePath: 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
    }
  );

  page = await context.newPage();
  await page.goto('http://localhost:3000/');
});

test.afterEach(async () => {
  await page.close();
  await context.close();
});

test('Sample test', async () => {
  await page.click('text=Open popup');
  await page.click('_react=Button >> nth=0');
  await page.click('text=Close popup');
});

I'm trying to create a function that will call hooks test.beforeEach() and test.afterEach() and the code inside them.

In the Playwright Issue page, it says that I need to move it to a separate Node module and then I would be able to use it but I'm struggling to understand how to do it.

CodePudding user response:

The example you're giving can be solved by implementing a custom fixture. Fixtures are @playwright/test's solution to customizing/extending the test framework. You can define your own objects (similar to browser, context, page) that you inject into your test, so the test has access to it. But they can also do things before and after each test such as setting up preconditions and tearing them down. You can also override existing fixtures.

For more information including examples have a look here: https://playwright.dev/docs/test-fixtures

  • Related