admin管理员组

文章数量:1292041

I want to be able to use a locator variable within all the tests without having to define it every time inside each test. Something like:

// @ts-check
const { test, expect } = require('@playwright/test');

test.beforeEach( async ({ page }) => {
  await page.goto('[desired URL]');  
});

// I want to make this variable global to be able to use it within all the tests.
const signInBtn = page.getByTestId('some-button'); // how to resolve 'page' here??

test.describe('My set of tests', () => {

  test('My test 1', async ({ page }) => {
    await expect(page).toHaveTitle(/Some-Title/);
    await expect(signInBtn).toBeEnabled();     // I wanna use the variable here...
  });
  
  test('My test 2', async ({ page }) => {
    await signInBtn.click();   // ...and here, without having to define it every time inside each test.
  });

});

PS: This snippet is just an example to pass the idea, not the actual project, pls don't be attached to it.

I want to be able to use a locator variable within all the tests without having to define it every time inside each test. Something like:

// @ts-check
const { test, expect } = require('@playwright/test');

test.beforeEach( async ({ page }) => {
  await page.goto('[desired URL]');  
});

// I want to make this variable global to be able to use it within all the tests.
const signInBtn = page.getByTestId('some-button'); // how to resolve 'page' here??

test.describe('My set of tests', () => {

  test('My test 1', async ({ page }) => {
    await expect(page).toHaveTitle(/Some-Title/);
    await expect(signInBtn).toBeEnabled();     // I wanna use the variable here...
  });
  
  test('My test 2', async ({ page }) => {
    await signInBtn.click();   // ...and here, without having to define it every time inside each test.
  });

});

PS: This snippet is just an example to pass the idea, not the actual project, pls don't be attached to it.

Share Improve this question asked Jan 10, 2023 at 17:33 GusGus 591 silver badge3 bronze badges 2
  • Don't use globals shared between tests like this. Each test should be self-contained. The page does a totally fresh navigation between tests. You could use a beforeEach block though. – ggorlen Commented Jan 10, 2023 at 22:39
  • You might want to check out the page object pattern. – Christian Baumann Commented Jan 11, 2023 at 9:14
Add a ment  | 

3 Answers 3

Reset to default 7

You don't have to.

Use Page Object Model..

Keep the tests clean and DRY.

page object model is an well known & time tested automation design pattern which separates out locator definitions and test method definitions from the actual test to keep it simple, clean & reusable.

See below example:

//Page Object

// playwright-dev-page.js
const { expect } = require('@playwright/test');

exports.PlaywrightDevPage = class PlaywrightDevPage {

  /**
   * @param {import('@playwright/test').Page} page
   */
  constructor(page) {
    this.page = page;
    this.getStartedLink = page.locator('a', { hasText: 'Get started' });
    this.gettingStartedHeader = page.locator('h1', { hasText: 'Installation' });
    this.pomLink = page.locator('li', { hasText: 'Guides' }).locator('a', { hasText: 'Page Object Model' });
    this.tocList = page.locator('article div.markdown ul > li > a');
  }

  async goto() {
    await this.page.goto('https://playwright.dev');
  }

  async getStarted() {
    await this.getStartedLink.first().click();
    await expect(this.gettingStartedHeader).toBeVisible();
  }

  async pageObjectModel() {
    await this.getStarted();
    await this.pomLink.click();
  }
}

Now we can use the PlaywrightDevPage class in our tests.

// example.spec.js
const { test, expect } = require('@playwright/test');
const { PlaywrightDevPage } = require('./playwright-dev-page');

test('getting started should contain table of contents', async ({ page }) => {
  const playwrightDev = new PlaywrightDevPage(page);
  await playwrightDev.goto();
  await playwrightDev.getStarted();
  await expect(playwrightDev.tocList).toHaveText([
    `How to install Playwright`,
    `What's Installed`,
    `How to run the example test`,
    `How to open the HTML test report`,
    `Write tests using web first assertions, page fixtures and locators`,
    `Run single test, multiple tests, headed mode`,
    `Generate tests with Codegen`,
    `See a trace of your tests`
  ]);
});

test('should show Page Object Model article', async ({ page }) => {
  const playwrightDev = new PlaywrightDevPage(page);
  await playwrightDev.goto();
  await playwrightDev.pageObjectModel();
  await expect(page.locator('article')).toContainText('Page Object Model is a mon pattern');
});

Reference: https://playwright.dev/docs/pom https://www.selenium.dev/documentation/test_practices/encouraged/page_object_models/

I would prefer a more simple solution here. You can just convert your variable to a function. You can keep your code as it's and do this change

const signInBtn = (page) => await page.getByTestId('some-button');

// then you can call it from anywhere
singInBtn(page)

You could move it all into a describe block. So something like this should work:

test.describe('My set of tests', () => {
   let signInBtn:Locator;

  test.beforeEach( async ({ page }) => {
    await page.goto('[desired URL]');
    signInBtn = page.getByTestId('some-button');
  });

  test('My test 1', async ({ page }) => {
    await expect(page).toHaveTitle(/Some-Title/);
    await expect(signInBtn).toBeEnabled();     
  });

  test('My test 2', async ({ page }) => {
    await signInBtn.click();  
  });

});

本文标签: Playwright JavaScriptHow can I reuse locator variables within different testsStack Overflow