Playwright code generation using ChatGPT

Shiv Jirwankar
6 min readDec 27, 2022

--

ChatGPT has taken the world by storm with its powerful AI chatbot capabilities. I have been using it for the past couple of days and the results have just blown my mind.

I have searched for some Javascript and Typescript code snippets while playing with ChatGPT and I was amazed to see the chat results. It just not generates the code snippet, but also adds the descriptions of what specific line(s) of code is doing which makes it easier to understand.

I then thought of asking for some code snippets related to Playwright automation with Javascript/Typescript and again it gave some outstanding results. Let’s have a look at ChatGPT’s response to different scenarios related to the Playwright. Please note that the description after the code is coming from ChatGPT itself.

Query 1: Playwright code for validating a button is visible in Typescript

Response:

Here is an example of how you might use Playwright and TypeScript to validate that a button is visible on a web page:

import { chromium } from 'playwright';

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');

// Validate that a button is visible on the page
const button = await page.$('button#my-button');
const buttonVisible = await button.isIntersectingViewport();
if (buttonVisible) {
console.log('Button is visible');
} else {
console.log('Button is not visible');
}

await browser.close();
})();

This code will launch a Chromium browser, navigate to the specified URL, and then search for a button element with an ID of 'my-button'. It will use the isIntersectingViewport method to determine whether the button is visible on the page (i.e., whether it is within the viewport). If the button is visible, it will log a message to the console indicating that the button is visible. If the button is not visible, it will log a message indicating that the button is not visible.

You can modify this code to search for different elements or to use other methods to determine the visibility of an element. You can also use Playwright's various debugging and testing features to automate the process of validating the visibility of elements on a page.

Query 2: Playwright code for sending a POST request and validating the response using Javascript

Response:

Here is an example of how you might use Playwright and JavaScript to send a POST request and validate the response:

const { chromium } = require('playwright');

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();

// Send a POST request and get the response
const response = await page.goto('https://example.com/api/endpoint', {
method: 'POST',
body: JSON.stringify({ key: 'value' }),
headers: { 'Content-Type': 'application/json' },
});

// Validate the response status and body
if (response.status() === 200) {
console.log('Response status is 200');
} else {
console.log(`Response status is ${response.status()}`);
}

const body = await page.evaluate(() => document.body.textContent);
if (body.includes('Expected Text')) {
console.log('Expected text found in response body');
} else {
console.log('Expected text not found in response body');
}

await browser.close();
})();

This code will launch a Chromium browser, send a POST request to the specified URL with a JSON body, and then get the response. It will validate the response status code and the response body by checking for the presence of a specific string of text ('Expected Text'). If the status code is 200 and the text is found in the body, it will log a message to the console indicating that the response is valid. If either the status code is not 200 or the text is not found in the body, it will log a message indicating that the response is not valid.

You can modify this code to customize the request and the validation criteria to fit your specific needs. You can also use Playwright's various debugging and testing features to automate the process of sending requests and validating responses.

Query 3: Playwright code to validate the visual UI of a webpage using Javascript

Response:

Here is an example of how you might use Playwright and JavaScript to validate the visual UI of a web page:

const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// Take a screenshot of the entire page
const screenshot = await page.screenshot();
// Compare the screenshot to a baseline image
const comparisonResult = await page.compareScreenshot(screenshot, 'baseline.png', {
threshold: 0.01,
});
// Log the result of the comparison
if (comparisonResult.misMatchPercentage === 0) {
console.log('UI matches baseline');
} else {
console.log(`UI differs from baseline by ${comparisonResult.misMatchPercentage}%`);
}
await browser.close();
})();

This code will launch a Chromium browser, navigate to the specified URL, and then take a screenshot of the entire page. It will then compare the screenshot to a baseline image (‘baseline.png’) using the compareScreenshot method. The comparison will return a result object containing a misMatchPercentage property that indicates the percentage of pixels that differ between the two images. If the misMatchPercentage is 0, it will log a message to the console indicating that the UI matches the baseline. If the misMatchPercentage is not 0, it will log a message indicating the percentage of difference between the two images.

You can modify this code to customize the comparison criteria or to compare specific elements or regions of the page rather than the entire page. You can also use Playwright’s various debugging and testing features to automate the process of validating the visual UI of a web page.

Query 4: Playwright code to validate web alert text on Firefox browser using JS

Response:

Here is an example of how you might use Playwright and JavaScript to validate the text of a web alert on a Firefox browser:

const { firefox } = require('playwright');
(async () => {
const browser = await firefox.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// Trigger an alert on the page
await page.evaluate(() => alert('Alert Text'));
// Get the text of the alert
const alertText = await page.getAlertText();
// Validate the alert text
if (alertText === 'Alert Text') {
console.log('Alert text is correct');
} else {
console.log(`Alert text is incorrect: ${alertText}`);
}
// Close the alert
await page.acceptAlert();
await browser.close();
})();

This code will launch a Firefox browser, navigate to the specified URL, trigger an alert on the page with the text ‘Alert Text’, and then get the text of the alert. It will validate the alert text by comparing it to the expected text. If the text is correct, it will log a message to the console indicating that the alert text is correct. If the text is incorrect, it will log a message indicating the actual text of the alert. Finally, it will close the alert by using the acceptAlert method.

You can modify this code to customize the alert text or to use different methods to interact with the alert (e.g., dismissAlert to cancel the alert). You can also use Playwright's various debugging and testing features to automate the process of validating web alerts.

Conclusion

As you can observe by looking at the generated code, ChatGPT has done a pretty decent job to get the workable code for us in no time. There is scope for improvement for sure since it is a newly launched product. One notable thing which I have observed is that it needs to be using the features which are introduced in the recent versions of Playwright. Like Locator API, assertions using expect’s in-built functions, etc. Maybe we can see those in the coming days once it will be trained accordingly. I really liked the text description and commented line of code which makes the code more understandable.

Of course, we do have the Playwright’s in-built auto-code generation feature which is more recommendable. But ChatGPT also looks promising given the fact that it is just newly launched and yet it is able to deliver some astonishing results.

--

--