Ask Your Question
3

In Playwright JavaScript, what is the method to reuse locator variables across various tests?

asked 2023-07-09 08:16:06 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-09 08:21:02 +0000

lakamha gravatar image

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();
  });
});
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-09 08:16:06 +0000

Seen: 12 times

Last updated: Jul 09 '23