How To Handle Inputs and Buttons In Playwright

OVERVIEW

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.

...

Single Input Field

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

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())
 
 
})

GitHub

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.

playwright test congf

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");

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"));

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")

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.
simple form demo

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

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();

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())

GitHub.

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.
...

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:

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)
 
})

two input fields

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']")

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()

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

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());

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)

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.

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();


})
lambdaTest selenium playground

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")

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();

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();

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

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.

specific tests with playwright
...

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!

Frequently Asked Questions (FAQs)

How do you run a single test in Playwright?

In Playwright, executing specific tests is easier. At the beginning of the test block, we must add “only” with “test”. After that, when you run the test, only that test will get executed.

Which language is better for Playwright?

A playwright is Microsoft’s open-source framework that can work with Javascript, Python, Java, and C# and also supports Chromium, Firefox, and Webkit.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Did you find this page helpful?

Helpful

NotHelpful