Recently I have been asking questions regarding Playwright and so far the community has been very helpful. I hope that my question and answers provided will be in use for people who are just starting with Playwright.
I have been working on the framework set up in Playwright. Framework consists of Mocha, Chai and uses Node.js. While reading https://playwright.dev/ I came a cross a section about using Page Objects approach. However the example which was posted is different from the ones which I am used and currently would like to implement in my solution. I am new to Playwright and Node.js so maybe someone who has more experience or maybe already worked with Page Object Pattern in Playwright will help. I am placing the code which was an example in the documentation and below the code my way of how I would like to have. I am open for any suggestions/improvements/comments from your side.
Example in documentation -> https://playwright.dev/docs/pom
-- Page Object Class set up--
// models/Search.js
class SearchPage {
constructor(page) {
this.page = page;
}
async navigate() {
await this.page.goto('https://bing.com');
}
async search(text) {
await this.page.fill('[aria-label="Enter your search term"]', text);
await this.page.press('[aria-label="Enter your search term"]', 'Enter');
}
}
module.exports = { SearchPage };
-- Test implementation --
// search.spec.js
const { SearchPage } = require('./models/Search');
// In the test
const page = await browser.newPage();
const searchPage = new SearchPage(page);
await searchPage.navigate();
await searchPage.search('search query');
-- My (if possible) implementation of the Page Object Class --
// models/Search.js
class SearchPage {
constructor(page) {
this.page = page;
}
// Separate URL with Locators
const bingUrl = "https://bing.com";
const searchField = '[aria-label="Enter your search term"]';
async navigate() {
await this.page.goto(bingUrl);
}
async search(text) {
await this.page.fill(searchField, text);
await this.page.press(searchField, 'Enter');
}
}
module.exports = new SearchPage();
-- My (if possible) implementation of the test --
// search.spec.js
const { SearchPage } = require('./models/Search');
// In the test
await SearchPage.navigate();
await SearchPage.search('search query');
If the solution is good, then I am planning on adding new automated test which will for sure reuse the existing page objects. A part from the mentioned questions above, if my solution is good then is it possible to use it with other future tests? From what I heard, when you export modules as new instance of classes you can run into cashed issues. If that so then what would be the correct approach? Also if you see any better suggestions on how I can implement Page Object Patter in Node.js let me know.
Thanks in advance and as always or help is welcomed.