DEV Community

Cover image for Write a Playwright test using AWS Lambda
QAProEngineer
QAProEngineer

Posted on • Updated on

Write a Playwright test using AWS Lambda

  1. Create a Playwright Test Script:

Write your Playwright test script in a Node.js environment. Here's a simple example using Playwright to open a webpage and take a screenshot:
`const { chromium } = require('playwright');

exports.handler = async (event) => {
let browser;
try {
browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();

await page.goto('https://example.com');
await page.screenshot({ path: '/tmp/example.png' });

await browser.close();

return {
  statusCode: 200,
  body: JSON.stringify({ message: 'Screenshot taken!' }),
};
Enter fullscreen mode Exit fullscreen mode

} catch (error) {
console.error('Error:', error);

return {
  statusCode: 500,
  body: JSON.stringify({ error: 'Internal Server Error' }),
};
Enter fullscreen mode Exit fullscreen mode

} finally {
if (browser) await browser.close();
}
};`

  1. Package Dependencies:

Since AWS Lambda has limited space for dependencies, you should use a tool like serverless or AWS SAM to package your Lambda function along with its dependencies. Ensure that you package Playwright and any other required Node.js modules.

3.Deploy to AWS Lambda:

Use AWS CLI or a deployment tool like serverless or AWS SAM to deploy your Lambda function to AWS.

4.Configure Lambda Function:

In the AWS Lambda console, set up your function. You'll need to configure the following:

** Runtime:** Node.js (Choose the version according to your script's requirements).
** Handler:** The name of your Lambda function and the exported function (e.g., filename.handler).
Memory: Set memory as per your requirements.
** Timeout:** Set the timeout duration for your function. Ensure it's long enough to complete your Playwright test.
** Execution Role:** Create an IAM role that allows the Lambda function to execute other AWS services and resources as needed.

5.Create an API Gateway (Optional):

If you want to trigger your Lambda function via an HTTP request, you can create an API Gateway and configure it to invoke your Lambda function.

6.Testing the Lambda Function:

You can now test your Lambda function by invoking it either through the AWS Lambda console or by making an HTTP request if you set up API Gateway.

Top comments (0)