Locators Reusability | Bondar Academy
Course: Playwright UI Testing with TypeScript
Module: Locators and Assertions
Instructor: Artem Bondar
Lesson Summary
In this lesson, you will learn about the importance of reusing locators in your code to enhance organization and reduce duplication. Reusing locators is a key step in optimizing your code. Lesson Overview The lesson begins with a simple scenario of automating a basic form, which includes: Typing an email Entering a password Clicking the submit button Initial Code Implementation The initial commands used to interact with the form include: basicForm.getByRole('email').fill('[email protected]'); basicForm.getByRole('password').fill('welcome123'); basicForm.getByRole('button').click(); After running the test successfully, it is noted that there is significant code duplication with the basicForm locator repeated multiple times. Refactoring the Code To eliminate duplication, the locator can be assigned to a constant: const basicForm = ...; This allows for cleaner code by replacing all instances of the full locator with the constant basicForm . Creating Additional Constants Further abstraction can be achieved by creating constants for specific elements: const emailField = basicForm.getByRole('email'); This allows for even simpler interactions: emailField.fill('[email protected]'); Assertions The lesson concludes with the introduction of assertions using the expect function from the Playwright library: await expect(emailField).toHaveValue('[email protected]'); Summary To reduce code duplication: Reuse locators by assigning them to constants. Increase abstraction by creating new constants from existing ones. Implement assertions to validate your tests. Thank you for watching, and see you in the next lesson!