Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In Playwright JavaScript, we can reuse locator variables across various tests by defining them in a separate file and exporting them as a module. Then, we can import them in the test files where we want to use them. Here is an example:

  1. Create a file named locators.js and define some locators:
const { Locator } = require('playwright');

const myButton = Locator('button[data-testid="my-button"]');
const myInput = Locator('input[data-testid="my-input"]');
const myLink = Locator('a[data-testid="my-link"]');

module.exports = {
  myButton,
  myInput,
  myLink,
};
  1. In your test files, import the locators from locators.js:
const { myButton, myInput, myLink } = require('./locators');

describe('My test suite', () => {
  test('My test case', async () => {
    const page = await browser.newPage();
    await page.goto('https://example.com');

    // Use the locators here
    await myInput.type('Hello, world!');
    await myButton.click();
    await myLink.click();

    await page.close();
  });
});