Reputation: 31
I'm making a C# Playwright test platform. I have a a list of strings I want to iterate through representing various locators on a page eg "GetByText("foo")", or GetByRole("AriaRole.Link, new() {Name="bar"})". I'd like to validate that each locator is present on my IPage, but I'm struggling with getting from string to ILocator for the assert step. Is there maybe a library out there that can perform this conversion, or will I have to write some bulky utility function to cover it?
I tried using page.Locator(locatorString) as seen below, but that doesn't seem to be how page.Locator is intended to be used.
using Microsoft.Playwright;
using NUnit.Framework;
public class DashboardTests : ContextTest {
[Test]
[TestCase("GetByText(\"foo\")")]
[TestCase("GetByRole(AriaRole.Link, new() {Name=\"bar\"})")]
public async Task ValidateElements(string locatorString) {
IPage page = await Context.NewPageAsync();
await page.GotoAsync("mypage.com");
await Expect(page.Locator(locatorString)).ToBeVisibleAsync();
}
}
Upvotes: 0
Views: 60
Reputation: 18328
The Page.Locator( <string> )
syntax is used for css or xpath selectors, as specified in the Playwright .NET documentation.
If you want to use the GetByText
or GetByRole
functionality, you'd be better off being more specific:
[Test]
[TestCase("text", "foo")]
[TestCase("role", "bar")]
[TestCase("css", "button")]
public async Task ValidateElements(string type, string value)
{
IPage page = await Context.NewPageAsync();
await page.GotoAsync("mypage.com");
Locator locator = null;
switch( type )
{
case "text":
{
locator = page.GetByText(value);
break;
}
case "role":
{
locator = page.GetByRole(AriaRole.Link, new() { Name=value});
break;
}
case "css":
{
locator = page.Locator(value);
break;
}
default: {
throw new NotImplemented("Nope.");
}
}
await Expect(locator).ToBeVisibleAsync();
}
Upvotes: 0