我希望能够在所有测试中使用定位器变量,而不必每次在每个测试中都定义它。 像这样的东西:
// @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:此代码片段只是一个传递想法的示例,并非实际项目,请勿附加。
最佳答案
您不必使用 Page Object Model. .
保持测试干净。
通过使用page object model这是一个众所周知且耗时考验的自动化design pattern我们将定位器定义和测试方法定义与实际测试分开,以保持简单、干净和可重用。
参见下面的示例:
//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();
}
}
现在我们可以在测试中使用 PlaywrightDevPage 类。
// 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 common pattern');
});
引用: https://playwright.dev/docs/pom https://www.selenium.dev/documentation/test_practices/encouraged/page_object_models/
关于javascript - Playwright JavaScript - 如何在不同的测试中重用定位器变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75073778/