CHAPTERS
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.
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:
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())
})
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");
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 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")
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.
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
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();
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())
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
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:
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)
})
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 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 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)
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.
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:
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();
})
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.)
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.
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.
LambdaTest’s automation testing cloud also supports Selenium, Cypress, Puppeteer, and even app automation frameworks such as Appium, Espresso, XCUITest, etc.
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!
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.
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!!
Did you find this page helpful?