DEV Community

Cover image for Playwright tutorial: How To Handle Inputs And Buttons In Playwright
Mehul Gadhiya
Mehul Gadhiya

Posted on

Playwright tutorial: How To Handle Inputs And Buttons In Playwright

As per StateofJS 2021 survey, Playwright has gained popularity in contrast to prominent JavaScript testing framework, with the awareness percentage rising from 19% to a whopping 34% in just a single year 2020–2021.

A playwright is an open-source test automation framework that lets you execute automated browser testing. You can automate any form of browser interaction using Playwright automation, be it a drag and drop, handling input values, or interacting with buttons (radio or checkboxes), etc.

This tutorial will help you, deep dive, into automating input values and button interaction with the Playwright testing framework. You’ll be starting off by automating a single input field and will get onto automating two input fields as well. You will also learn to automate button interaction with Playwright using checkboxes, along with bonus test scenarios to automate with the Playwright testing framework.

Need a list of names for your project or looking a way to find cool and funky names? Use our Random Name Generator tool to generate unique and creative names instantly.

Single Input Field

There are multiple Playwright testing inputs that you can leverage to automate interaction with a single input field. These would include

  • getAttribute

  • Playwright expect

  • toHaveAttributet

  • scrollIntoViewIfNeeded

  • inputValue

Let’s take a basic test scenario of a demo page on LambdaTest Selenium Playground to validate and try these Playwright inputs.

Test scenario:

  • Go to Simple Form Demo on LambdaTest Selenium Playground.

  • Click on the single input field with the placeholder text ”Please enter your message”.

  • Add the text and click the button to get values checked in the result.

With the help of the test script given below, we will test for a Placeholder text in an empty inbox and the result once we enter our value.

import { expect, test } from "@Playwright/test";

 import { expect, test } from "@playwright/test";

test("Interaction with inputs", async ({ page }) => {

    await page.goto("https://www.lambdatest.com/selenium-playground/simple-form-demo");
    const messageInput = page.locator("input#user-message");
    await messageInput.scrollIntoViewIfNeeded();
    console.log(await messageInput.getAttribute("placeholder"));
    expect(messageInput).toHaveAttribute("placeholder", "Please enter your Message")
    console.log('Before entering data: ' + await messageInput.inputValue());
    await messageInput.type("Hi koushik");
    console.log('After entering data: ' + await messageInput.inputValue())


})
Enter fullscreen mode Exit fullscreen mode

Before starting, create a ‘basicinteraction.test.ts’ file in the test folder. Rename the config file within testmatch with the file we have generated. So it will become our execution point now.

After creating a new file, we will understand every step with the functions it includes.

First, define page and the element where you want to perform the test.

await page.goto("https://www.lambdatest.com/selenium-playground/simple-form-demo");
const messageInput = page.locator("input#user-message");
Enter fullscreen mode Exit fullscreen mode

Need fake addresses for your testing needs? Try our Random Fake Address Generator tool to quickly generate unique and random fake addresses as many as you want in no time.

getAttribute

getAttribute is used to fetch the value of the specified attribute on elements.

You want to test that when the inbox is empty, there should be some text that users can read, and for that, you have to add a console log and use the getAttribute command. And add the attribute name as a “placeholder.”

console.log(await messageInput.getAttribute("placeholder"));
Enter fullscreen mode Exit fullscreen mode

Say goodbye to insecure passwords and unprotected data. Protect your sensitive data with our RipeMD160 Hash Calculator. Generate secure hashes with just a few clicks.

Playwright expect

“Playwright expects” is a library to test assertions. So it helps you to test your assumption about your program. Here, use the “expect” function to add “please enter your message” as a placeholder.

expect(messageInput).toHaveAttribute("placeholder", "Please enter your Message")
Enter fullscreen mode Exit fullscreen mode

Need to create MD5 hashes quickly? Our MD5 hash calculator create reliable, one-way hashes quickly and keep your information secure. Try it out now.

toHaveAttribute

getAttribute will only print action, but to input values, you have to use the Expect command. So import expect command from the Playwright testing framework to assert essence for placeholder.

We have to use the toHaveAttribute command to add attribute value and expected value.

  • Press Ctrl + J to open the terminal and run the test. When you run the test, it will open the Chromium browser.

  • It navigates to the URL and types the value to run the test, as shown in the screenshot.

You can also open a reporter separately by navigating the path below.

Click on Folder (test results) > Reveal in file explorer > Playwright — Reports >Index.html

Make your data tamper-proof with our SHA256 Hash Calculator. Create secure, one-way hashes for your data in no time. Start creating your hashes now.

scrollIntoViewIfNeeded

In the test result, we get a screenshot and video of actions. But usually, the entire page needs to be visible due to browser size. So for scrolling down, we use the scrollIntoViewIfNeeded command.

await messageInput.scrollIntoViewIfNeeded();
Enter fullscreen mode Exit fullscreen mode

Stop worrying about data security. Our SHA512 hash calculator can help you protect your information from unauthorized access. Create secure hashes quickly and easily.

inputValue

After testing the empty inbox, verify whether the data you put in the inbox is getting stored, processed, or not.

For that, use the InputValue function to check whether what you are typing is getting stored.

inputValue has the same structure as getAttribute, but in inputValue, brings the value of whatever you pass in the inbox. In getAttribute, you must give the attribute name to get the value.

You can continue with the same test and add a locator with a type action like the one mentioned below.

console.log('Before entering data: ' + await messageInput.inputValue());
                                    await messageInput.type("Hi koushik");
                                    console.log('After entering data: ' + await messageInput.inputValue())
Enter fullscreen mode Exit fullscreen mode

For better understanding, we will add two console logs, “Before entering data” and “ after entering data”. Before entering data,” for an empty inbox and “after entering data” will be tested for the value we passed.

Now rerun the test.

As a result, we get a

  • placeholder value” Please enter your message”,

  • “before entering data,” which is empty, and

  • “after entering data,” which will be the value we added.

**Need to make your JSON code more readable? Our online JSON Prettifier tool makes your JSON data more human-readable. Copy, paste, and prettify in seconds. **

Two Input Fields

So we completed the test script for the single input field. Now we will go after a slightly complex scenario about automation tests in playwright automation. Testing two input fields are similar to a single input with additional functions. We will take look while writing the test script. Some functions this test includes are:

  • textContent

  • toHaveText

  • type and fill commands

Test scenario:

  • Go to simple form demo on LamabdaTest selenium playground

  • In two input fields, define elements for inboxes, buttons, and result box

  • Add value in two empty inboxes

  • Click on the “Get value” button, which will give us the result or the sum of values in the result bar.

Here is the test script for testing two input fields.

import { expect, test } from "@Playwright/test";

 test("Sum", async ({ page }) => {
    await page.goto("https://www.lambdatest.com/selenium-playground/simple-form-demo");
    const sum1input = page.locator("#sum1")
    const sum2input = page.locator("#sum2")

    const getValuesBtn = page.locator("//button[text()='Get values']")
    let num1 = 121;
    let num2 = 546
    await sum1input.fill("" + num1);
    await sum2input.type("" + num2);
    await getValuesBtn.click()
    const result = page.locator("#addmessage")
    console.log(await result.textContent());
    let expectedResult = num1 + num2;
    expect(result).toHaveText("" + expectedResult)

})
Enter fullscreen mode Exit fullscreen mode

Step 1: Firstly, define pages and elements for inboxes and buttons.

test("Sum", async ({ page }) => {
                                await page.goto("https://www.lambdatest.com/selenium-playground/simple-form-demo");
                                 const sum1input = page.locator("#sum1")
                                const sum2input = page.locator("#sum2")
                                const getValuesBtn = page.locator("//button[text()='Get values']")
Enter fullscreen mode Exit fullscreen mode

As you see, Playwright is smart enough to understand when you add CSS ID or XPath ID and will use “//” or “#” accordingly.

Step 2: Define num1 and num2; we can’t add numbers directly because you will require strings for the type command.

**Step 3: **With the help of the “type” and “fill” commands, add num 1 and num 2.

Step 4: Likewise, for testing the “get value” button, use the “click” action.

await sum1input.fill("" + num1);
await sum2input.type("" + num2);
await getValuesBtn.click()
Enter fullscreen mode Exit fullscreen mode

These are the steps for defining our inputs and clicking buttons. Now, we need to check the result bar.

**Get faster loading times and better user experience with our efficient JSON minify tool. Quickly compress your JSON data with ease and optimize your website now. **

textContent

textContent is a function that will return the text present in particular elements. It returns the text content of the specified node and all its descendants.

Once you do the sum of both numbers, you need to check that you are getting the result at the result bar; that’s why use the textContent function.

const result = page.locator("#addmessage")
console.log(await result.textContent());
Enter fullscreen mode Exit fullscreen mode

Our HTML Minify is a perfect tool for anyone looking to optimize website’s speed. Minify your code and optimize website for faster loading times in few seconds.

toHaveText

toHaveText is like getText in Selenium. It helps to retrieve the text content, and then do the value. It checks that the element text is similar to the expected text.

Here you want the answer in the result bar, so do an assertion with expect command with toHaveText.

let expectedResult = num1 + num2;
expect(result).toHaveText("" + expectedResult)
Enter fullscreen mode Exit fullscreen mode

Make your XML code easy to read and understand with our free online XML Prettify tool. Format your code for better readability and save time.

type and fill commands

We use type and fill commands when we need to add text to the inbox. Both serve the same purpose but represent differently.

When we want to type one character at a time, we can use ‘type’, and if we want to add data whole at once, we can use ‘fill’. So fill will clear the existing value and pass new fresh data. It shows the entire data instantly on a screen.

Tired of unorganized YAML code? Our YAML Beautifier tool makes YAML code easy to read and understand. Simply paste your code and produce well-formatted document in seconds.

Interaction with Checkboxes in Playwright

We learned how to automate testing for Inputs in playwright automation. Next up is automating button interaction through Playwright testing. The Playwright testing framework has functions that help us to write tests for Buttons here, for example, we have used a checkbox.

Test Scenario:

  • Go to the checkbox demo page on LambdaTest Selenium Playground

  • Check that checkbox is unchecked

  • After the interaction check, that checkbox is checked

Here is the test script and screenshot for the testing checkbox.

est("Checkbox", async ({ page }) => {

 await page.goto("https://www.lambdatest.com/selenium-playground/checkbox-demo")
 const singleCheckbox = page.locator("id=isAgeSelected")
 expect(singleCheckbox).not.toBeChecked();
 await singleCheckbox.check();
 expect(singleCheckbox).toBeChecked();


})
Enter fullscreen mode Exit fullscreen mode

Step 1: Define the page URL and its element; while defining elements, you can use its CSS value, but for example, we have used its id.

test("Checkbox", async ({ page }) => {

await page.goto("https://www.lambdatest.com/selenium-playground/checkbox-demo")
const singleCheckbox = page.locator("id=isAgeSelected")
Enter fullscreen mode Exit fullscreen mode

P.S. — Another way to find elements is to use the “$” symbol, which is less recommendable in the updated version of the Playwright. Using a locator is the best practice.

Step 2: By default, the checkbox is unchecked, so you have to add an assertion with the help of the expert function. For testing, that checkbox is checked in Playwright and has the command “toBeChecked”. But the default checkbox is unchecked, and Playwright doesn’t have a command for checking an empty checkbox, so you have to use “not” before “toBeChecked.”

expect(singleCheckbox).not.toBeChecked();
Enter fullscreen mode Exit fullscreen mode

Step 3: After testing an empty checkbox, write a test for the checkbox when users click on it or fill it. You can do it with the check() function. Now your checkbox will be checked or filled, so use “toBeChecked.” Now run the test.

await singleCheckbox.check();
expect(singleCheckbox).toBeChecked();
Enter fullscreen mode Exit fullscreen mode

P.S. (Using Click() will not change the result.)

Streamline your SQL code by removing unnecessary spaces and comments with our SQL minify tool that enhances your code’s readability and reduces size. Try it today.

Execute specific tests with Annotation in Playwright runner

The Playwright automation framework will run each test on different browsers when you have multiple test blocks and execute all tests simultaneously. However, when you want to execute one particular test, there are better practices than commenting on other tests to run one. There is an easy method to do it, and it is “Annotation in Playwright runner”.

You can add “only” before the test, and even if you have several test scripts in sequence, only the first test will execute.

Scaling Playwright Test Execution with LambdaTest

You can run a Playwright automation test over 50+ real browsers and operating systems with the help of LambdaTest. You can run multiple tests in Parallel and speed up your test execution for various browsers and OS.

  • Integrate seamlessly with your CI/CD pipelines.

  • Debug Playwright tests from a variety of logs such as network logs, command logs, and full video recordings.

  • Execute Playwright tests 70% faster than any testing cloud by leveraging Hyperexecute, the fastest end-to-end test orchestration cloud by LambdaTest.

  • Run Playwright tests in parallel on multiple configurations and trim down your test execution by multiple folds.

  • Organise your test analytics by creating custom dashboards and widgets.

LambdaTest’s automation testing cloud also supports Selenium, Cypress, Puppeteer, and even app automation frameworks such as Appium, Espresso, XCUITest, etc.

Conclusion

You made it up until here. We hope this blog clarifies handling inputs, functions, and assertions in Playwright testing. Also, functions and commands like getAttribute, Expect, scrolllntoViewIfNeeded, inputValue, textContent, etc. This will help you perform tests on web forms and checkboxes smoothly without any hurdles.

Follow the LambdaTest YouTube Channel to stay updated on Responsive testing, Mobile testing, Selenium testing, etc.

Playwright is easy; you only need basic knowledge of JavaScript and TypeScript. If you want to learn how to run tests with the help of Playwright automation, LambdaTest provides free Playwright 101 certification that will help you elevate your automation testing skills. We will continue learning in the following videos. So stay tuned!

Top comments (0)