Let's dive into creating a custom utility function in Playwright. We'll create a typeWithClear
function that clears an input field before typing new content.
First, we'll use the click
method with { clickCount: 3 }
to select all existing text in the input field. Then, we'll use the press
method with 'Backspace'
to delete the selected text.
Here's how you can do it:
import { Locator } from 'playwright';
async function typeWithClear(locator: Locator | undefined | null,
value: string,
options?: { delay?: number }): Promise<void> {
if (!locator) {
throw new Error('Locator not found');
}
await locator.click({ clickCount: 3 });
await locator.press('Backspace');
await locator.type(value);
}
This function takes three arguments:
.type()
call (such as { delay: number }
).The function first checks whether a valid locator was passed in. If not, it throws an error indicating that no valid locator was found. If there is a valid locator object present, then it clicks on it three times (to select all existing content), presses backspace once (to delete selected content), then types in new content using .type(value)
.
And there you have it! You've just created a custom utility function in Playwright. Happy testing!
If you still have questions, please ask a question and I will try to answer it.
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].