Learn how to leverage Playwright test fixtures to DRY your code and reuse it across tests and spec files.
In this video, we learn about a powerful, advanced feature of Playwright called test fixtures. Fixtures allow you to share code across different test cases in your Playwright code base. In fact, you might have already used fixtures unknowingly since Playwright provides predefined fixtures like page, context, browser, and browserName.
To better understand how fixtures work, we walk through the process of implementing a custom test fixture. In the example provided, we have a single Playwright test file that logs into a web application. When adding new test cases in the future, we'll need the same setup instructions to log into the web app and test the functionality.
To create a custom fixture, we can extend the test object coming from Playwright itself. We initialize a new variable called myTest
, then use test.extend
and define our test fixture, webApp
, which we then pass an async function and a use
function. The code is executed in the following order: Playwright runs the setup step, the actual test case, and then it calls whatever comes after the use
.
We now move the login logic into our custom fixture, allowing us to remove the page fixture and utilize webApp
instead. But we also need to specify that we want to use the page fixture inside our custom webApp
fixture.
To avoid having custom fixtures in our spec files, we can create a custom JavaScript file that exports the extended test function. We then require this setup file in our test file, clean up any unnecessary code, and call the test, ready to use the webApp
fixture across different spec files and test cases.
Test fixtures are a fantastic way to structure your Playwright project and reuse code across different test cases, making your testing process more efficient and organized.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].