Overview
Overview
mkdir playwrights_with_JavaScript
cd playwrights_with_JavaScript
npm init -y
This will create a new directory called "playwrights_with_JavaScript" and
initialize a new npm project inside it.
{
"name": "playwrights_with_javascript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"playwright": "^1.31.2"
}
}
Using the VS Code extension
Step 1: Create a folder, e.g., playwright_javascripts_1.31.
Step 2: Open the folder in VS Code.
Step 3: Search Playwright extension in VS Code and install it.
Step 4: Now Search “Playwright” and Click on Test: Install Playwright
Step 5: Finally, click the OK button.
Once you click on the “OK” button, installation of Playwright starts and
can be seen in the below screenshot after the final installation.
Types of Testing using Playwright
You can use Playwright for various types of testing using, including UI
Testing, API Testing, Visual Testing, Accessibility Testing, and Component
Testing. Each type of testing is explained in detail below with examples.
UI Testing with Playwright JavaScript
With Playwright, you can simulate user interactions such as clicking, filling
out forms, and navigating between pages to test the functionality of your
web application.
Let’s take an example of UI automation for the site:
https://ecommerce-playground.lambdatest.io/.
Use Case:
1. Open the site https://ecommerce-
playground.lambdatest.io/.
2. Clicking on ‘Mega Menu’ -> Desktop.
3. Click on 'Palm Treo Pro’.
4. Add item 'Palm Treo Pro’ into Cart.
5. Verify item 'Palm Treo Pro’ is displayed.
test("GET API Request with -- Valid 200 Response ", async ({ request })
=> {
const response = await request.get("${baseurl}/users/2");
expect(response.status()).toBe(200);
});
POST Request
A POST API request is a type of API request that is used to send data to a
server. It is often used to create or update resources on the server. In a
POST request, the client sends a payload (or request body) to the server,
which contains the data that needs to be processed or stored.
Below is the example of a POST request where we create the data, then
verify the status should be 201.
test("POST API Request with -- Valid 201 Response ", async ({ request })
=> {
const response = await request.post("${baseurl}/users/2', {
data: {
id: 123,
},
});
const responseBody = JSON.parse(await response.text());
expect(responseBody.id).toBe(123);
expect(response.status()).toBe(201);
});
PUT Request
A PUT API request is a type of HTTP request used in RESTful web services
for updating or replacing an existing resource on the server. In a PUT
request, the client sends a payload (or request body) to the server, which
contains the updated representation of the resource.
Below is the example of a PUT request where we are updating the id and
then verifying the status should be 200.
test("PUT API Request with -- Valid 201 Response ", async ({ request })
=> {
const response = await request.put("${baseurl}/users/2", {
data: {
id: 245,
},
});
const responseBody = JSON.parse(await response.text());
expect(responseBody.id).toBe(245);
expect(response.status()).toBe(200);
});
DELETE Request
A DELETE API request is a type of HTTP request used in RESTful web
services for deleting a resource on the server. In a DELETE request, the
client sends a request to the server to delete a resource identified by a
specific URI (Uniform Resource Identifier).
Below is the example where we delete the particular id, then verifying
status should be 204.
expect(await page.screenshot()).toMatchSnapshot('golden.png')
To save a screenshot, Playwright will utilize the page object and call the
screenshot function. Then, it will compare these two screenshots for visual
differences using the pixelmatch library. To fine-tune the pixel matching in
your screenshots, use the threshold option.
For a complete example, please see the snippet below:
});
')
Output
You can enhance the power of your Playwright visual regression testing
suite by executing your tests on cloud. SmartUI clouds like LambdaTest
provide a visual testing feature that allows you to capture screenshots of
web pages or specific elements on those pages and then compare them
against expected screenshots or baseline images. This enables you to
detect any visual differences or discrepancies in the layout, design, or
appearance of your web application across different configurations.
With LambdaTest, you can perform Playwright automated testing at scale
using our cloud-based digital experience testing platform, significantly
reducing the time required to run your Playwright JavaScript tests.
LambdaTest provides access to a comprehensive online browser farm of
over 50 different browser versions, including Chrome, Chromium,
Microsoft Edge, Mozilla Firefox, and WebKit, allowing you to execute your
Playwright JavaScript tests. This provides maximum coverage and
compatibility, enabling you to test your applications on various browser
environments.
cd react-app
npm start
Step 3: After running the above command, React app starts with
port http://localhost:3000/.
You can see in your Visual Studio Code, the project has been created
successfully. What it looks like is attached below.
Step 3: Now run the below command.
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Next step is to write out the test cases that we want to test and then
check if the component works as expected. Add the below code
under App.spec.js.
// @ts-check
const { test, expect, chromium } = require("@playwright/test");
test.describe("Open the Site and Serach the data ", () => {
test("Search the text 'Palm Treo Pro ", async ({ page }) => {
await page.goto('https://ecommerce-playground.lambdatest.io/');
await page.locator("span.title", {hasText: 'Mega Menu' }).hover()
await page.locator("a[title=Desktop]").click();
await page.locator("div.carousel-item.active > img[title='Palm Treo
Pro']").click()
await page.locator("#container button[title='Add to Cart']").click();
await page.locator("a.btn.btn-primary.btn-block",{hasText: 'View
Cart'}).click()
await expect(page.locator("td.text-left", {hasText: 'Palm Treo
Pro'})).toBeVisible()
await expect(page.locator("div[class$='flex-nowrap'] >
input")).toHaveValue("1")
});
})
First Method to Run Test Case
To run Playwright JavaScript test cases on the command line, you can use
the following Playwright test command:
We can execute the above code in the UI using the below command in two
browsers - Firefox and Chrome.
Flexibility
The cloud provides access to a wide range of browser and operating
system configurations, allowing you to test your web application on
various platforms.
Cost-effectiveness
Running your Playwright JavaScript tests on the cloud can be more cost-
effective than maintaining your own hardware and software infrastructure.
Parallel testing
Cloud-based testing platforms allow you to run your Playwright JavaScript
tests in parallel, which can significantly reduce the time it takes to
complete your test suite.
const capabilities = [
{
browserName: "Chrome", // Browsers allowed: 'Chrome', 'MicrosoftEdge',
'pw-chromium', 'pw-firefox' and 'pw-webkit'
browserVersion: "latest",
"LT:Options": {
platform: "Windows 11",
build: "Playwright Sample Build",
name: "Playwright Sample Test on Windows 11 - Chrome",
user: "username",
accessKey: "accesskey",
network: true,
video: true,
console: true,
},
},
{
browserName: "MicrosoftEdge",
browserVersion: "latest",
"LT:Options": {
platform: "Windows 11",
build: "Playwright Sample Build",
name: "Playwright Sample Test on Windows 8 - MicrosoftEdge",
user: "username",
accessKey: "accesskey",
network: true,
video: true,
console: true,
},
},
{
browserName: "Chrome",
browserVersion: "latest",
"LT:Options": {
platform: "MacOS Big sur",
build: "Playwright Sample Build",
name: "Playwright Sample Test on MacOS Big sur - Chrome",
user: "username",
accessKey: "accesskey",
network: true,
video: true,
console: true,
},
},
];
node UiTest_RunIn-parallel.js
Viewing your Playwright JavaScript Test Results
When Playwright JavaScript tests are executed on the LambdaTest
platform, the results are displayed in the LambdaTest Automation
Dashboard.
The Playwright build is displayed on the left in the LambdaTest Automation
Dashboard snapshot below, and the corresponding build sessions are
displayed on the right.
In the below screenshot, you can see the test case start executing on
different platforms.
Finally, you can see the test case is executed.