microsoft / playwright-dotnet

.NET version of the Playwright testing and automation library.
https://playwright.dev/dotnet/
MIT License
2.47k stars 235 forks source link

[Documentation] Custom selector engines before page is created #2750

Open Exoow opened 11 months ago

Exoow commented 11 months ago

The documentation (both in code and https://playwright.dev/dotnet/docs/extensibility) states: Selectors must be registered before creating the page.

However the code below works, in a TestClass inheriting from PageTest. Isn't the page already created when entering this method, given that actions are performed on it?

[TestInitialize]
public async Task InitializeTest()
{
    await RegisterCustomSelectors(); // register here
    await Page.GotoAsync("/");
    await Page.Locator("myengine=test").FillAsync("hi"); // this works!
}
Exoow commented 11 months ago

I found the caveat though: when running more than 1 test, Playwright throws an exception because the selector is already registered...

mxschmitt commented 11 months ago

Yes, there is currently no great way of adding a custom selector engine in .NET. TestInitialize is too late.

What kind of selector engine are you creating? We learned that for most users the integrated selector engines are enough.

Exoow commented 11 months ago

In TestInitialize works after adding a try/catch so it won't fail from the second test onwards.

We have tests running against Microsoft Dynamics, and it's easiest to select components by data-dyn-role or data-dyn-controlname attributes. So instead of css=[data-dyn-controlname=something] I can write ddc=something.

An alternative could be to write extension methods on IPage and ILocator for this, but I like the brevity of the custom selectors.