Why fixtures enable clean Playwright projects
But let’s take a step back first… Over time, more and more people have asked me how they should organize and structure complex Playwright projects. I don’t believe there’s a single silver bullet, however, I do like to establish some patterns that enable coding conventions and best practices. As mentioned above, one of these patterns is to rely on custom Playwright fixtures whenever possible. As the Playwright docs state, fixtures:- help to encapsulate setup and teardown in a single place.
- are reusable between tests.
- are lazy and only run when “requested” in your test cases.
- are composable to group functionality.
DashboardPage
into a fixture and Playwright itself, the test cases can focus on testing features. You don’t need to repeatedly add setup instructions that initialize page object models. Define that you want to use a dashboardPage in your test and receive a ready-to-use object. Great stuff!
But if your page object models need additional configuration, such as the user above, you might wonder how to pass additional arguments to your page object model constructors.
Let’s look at how this fixture is implemented and find out how we can configure it!
How to add options to your custom Playwright fixtures
Suppose you haven’t used fixtures before; here’s all the magic. Instead of importing test and expect from @playwright/test, your tests can import these from a base file that extends Playwright’s core functionality.base.ts
test
method allows you to enrich Playwright’s core functionality with your own custom fixtures and options. The trick is to import and rename test
, extend it with your custom additions, and then export the returned value as test
to be used in your test cases.
In the example above, the dashboard
fixture initializes the new DashboardPage
and then passes the result to the provided use
method. Whatever use
will be called with will be passed to your test cases. This has the advantage of having all your setup instructions in one place.
But if you now have test cases that should use the dashboardPage
object with different users, you can’t change how the page object model will be initialized because the setup is hidden away from the test cases.
How could we make this fixture setup configurable?
Configure your Playwright project with custom options
Similar to fixtures, Playwright allows you to define static values and options in our Playwright setup, and you can do it right next to your fixture definitions in the extend call.base.ts
base.ts
playwright.config.ts
to change the user object and set a different one in the global settings.
playwright.config.ts
playwright.config.ts
test.use
.
base.ts