To make the test more readable and reusable, I pass it to a page object with my own methods. By creating a fixture, I can make these methods available for use. The fixture structure consists of a before block, the test, and an after block. Instead of importing test and using page, I import and use my fixture on the test. This allows me to access the methods I created in the page object, making the code more readable and reusable. Playwright fixtures provide control over the methods used in the fixture, creating a small and controllable environment.
So this is a test that I created, and you can see that it's using the page fixture. I'm importing test from Playwright. I have a before it. I am checking for some titles and filling some forms. But this is not really reusable and you cannot really understand if you don't have the context of the application, what is being done here.
So how can I create this more easy to read and more reusable for everyone that needs to add tests to use it? So the answer is, I'm going to pass this to a page object that has my own methods. And you can see here that I have getTitle, clickButtons, fillForms. So this is my methods, my page objects, but this only by itself does not make them available on the page fixture.
So what I need to do to make them available to use is, well, create a fixture. So the structure here is, I need to have a function that is going to say to Playwright, add my fixture to the land of the feature. So test is the land of the features and I'm going to extend my own features. And in my fixture definition, there is going to be my test. You can use other fixtures like a fixture section to do stuff, but the main stuff here is the structure. So the structure for the fixture is going to be the before block, the test, and then the after block. So what I'm doing here is, if you look at the previous, the initial test, I have a before hook and comparing to my fixture, the same before hook is there. Then I'm going to use my methods in the initial page and after the run, I'm going to console.log something.
So how can I use this in my test? So instead of importing test, instead of using page, now what I'm going to do is import my fixture and use my fixture on the test and import my test that is the actual fixture. And as you can see there, it has access to my methods that I created in the page object. It's a little more readable and it's very reusable because if I want to have, let's say, another 10 tests that go through this, you can just reuse it instead of just having to recode everything. So the control that PlayWrite Fixtures gives us is I can decide what methods do I need to use or what I want to use in my fixture. I have a really small environment that is very controllable and very reusable. So, I hope that this gives you a little bit more of insight on fixtures and how you can use it in your tests. And that's it guys.
Comments