'Is it possible to get the selector from a locator object in playwright?
I'm using the page-object-model in developing my automated tests in playwright. As such, I'm building a class to hold my locators and expose the locators, but not necessarily the used selector. Does the locator have a way to share its selector?
exports.MyWebPageModel = class MyWebPageModel {
constructor(page) {
this.myMultiSelect = page.locator('#select-group select');
this.submitButton = page.locator('#submit-btn');
}
}
test('validate multi-select submission', ({page}) -> {
const myPage = new MyWebPageModel(page);
const selectChoices = ['choice1', 'choice2', 'choice4'];
await myPage.myMultiSelect.selectOptions(selectedChoices);
Promise.all([
page.waitForNavigation(),
myPage.submitButton.click()
]);
/* do tests on new page, click it's back button to return to previous page */
const allSelectedValues = await page.$eval(myPage.myMultiSelect.???, e => Array.from(e.selectedOptions).map(option => option.value)); // get the selected options from select element
expect(allSelectedValues).toEqual(selectedChoices); // verify the selected options matches selectChoices.
});
Solution 1:[1]
Well this is one way, but not sure if it will work for all possible locators!.
// Get a selector from a playwright locator
import { Locator } from "@playwright/test";
export function extractSelector(locator: Locator) {
const selector = locator.toString();
const parts = selector.split("@");
if (parts.length !== 2) { throw Error("extractSelector: susupect that this is not a locator"); }
if (parts[0] !== "Locator") { throw Error("extractSelector: did not find locator"); }
return parts[1];
}
Solution 2:[2]
I am 95% sure that you can not get the selector which was previuously used. However there is way to get selector by changing your class and making the selectors as public class attributes.
exports.MyWebPageModel = class MyWebPageModel {
//think it can be declared as const
public let multiSelectSelector:string = '#select-group select';
public let submitButtonSelector:string = '#submit-btn';
constructor(page) {
this.myMultiSelect = page.locator(this.multiSelectLocator);
this.submitButton = page.locator(this.submitButton);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Gaj Julije |