I'm Samuel FajreldinesI am a specialist in the entire JavaScript and TypeScript ecosystem (including Node.js, React, Angular and Vue.js) I am expert in AI and in creating AI integrated solutions I am expert in DevOps and Serverless Architecture (AWS, Google Cloud and Azure) I am expert in PHP and its frameworks (such as Codeigniter and Laravel). |
Samuel FajreldinesI am a specialist in the entire JavaScript and TypeScript ecosystem. I am expert in AI and in creating AI integrated solutions. I am expert in DevOps and Serverless Architecture I am expert in PHP and its frameworks.
|
Introduction
In today's competitive software landscape, delivering flawless user experiences is paramount. As web applications become increasingly complex, the importance of robust automated testing cannot be overstated. Enter Playwright, an innovative end-to-end testing framework developed by Microsoft. Playwright enables developers to write reliable, efficient, and powerful tests across all modern browsers using a single API.
In this guide, we'll delve into why Playwright has become a game-changer in web testing and provide a step-by-step tutorial on how to get started with creating tests using this powerful tool.
Choosing the right testing framework can significantly impact the efficiency and reliability of your testing process. Here are compelling reasons why Playwright stands out:
Playwright supports Chromium, Firefox, and WebKit, which means you can write one test and run it across all major browsers. This cross-browser functionality ensures consistent user experiences regardless of the browser used.
Playwright introduces the concept of browser contexts, which allow you to run multiple isolated sessions within a single browser instance. This feature dramatically speeds up test execution and reduces resource consumption.
One of the most common challenges in automated testing is dealing with dynamic content and timing issues. Playwright's auto-wait functionality waits for elements to be ready before performing actions, reducing flaky tests and improving reliability.
With first-class support for JavaScript, TypeScript, Python, Java, and .NET, Playwright's API is intuitive and leverages modern programming paradigms. This makes writing and maintaining tests more straightforward for developers.
Playwright offers advanced features like:
As an open-source project backed by Microsoft, Playwright is actively maintained and regularly updated with new features and improvements.
Let's dive into how you can start creating tests with Playwright.
Install Playwright via npm using the following command:
npm install --save-dev playwright
This command installs Playwright and downloads the browser binaries for Chromium, Firefox, and WebKit.
Create a new directory for your project and initialize npm:
mkdir playwright-tests
cd playwright-tests
npm init -y
If you prefer using TypeScript, install it:
npm install --save-dev typescript ts-node
Create a tsconfig.json
file:
{
"compilerOptions": {
"target": "ESNext",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"outDir": "dist"
}
}
Let's create a simple test to navigate to a website and verify its title.
Create a file named example.spec.js
(or example.spec.ts
if using TypeScript).
const { chromium } = require('playwright');
(async () => {
// Launch browser
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
// Open new page
const page = await context.newPage();
// Navigate to URL
await page.goto('https://www.example.com');
// Get page title
const title = await page.title();
console.log(`Page title: ${title}`);
// Close browser
await browser.close();
})();
Execute the test with the following command:
node example.spec.js
headless: false
opens the browser window so you can see the actions.page.goto()
to navigate to the desired website.To verify that the page title matches the expected value, we can include assertions using a testing framework like Jest or use Playwright Test, Playwright's built-in test runner.
Install Playwright Test:
npm install --save-dev @playwright/test
Update your test file:
// example.spec.js
const { test, expect } = require('@playwright/test');
test('Verify page title', async ({ page }) => {
await page.goto('https://www.example.com');
await expect(page).toHaveTitle('Example Domain');
});
Update your package.json
to include a test script:
"scripts": {
"test": "playwright test"
}
Run the test:
npm run test
Playwright makes it easy to run tests across different browsers. Update your test to run on Chromium, Firefox, and WebKit:
const { test, expect } = require('@playwright/test');
test.describe.configure({ mode: 'parallel' });
for (const browserType of ['chromium', 'firefox', 'webkit']) {
test(`Verify page title in ${browserType}`, async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://www.example.com');
await expect(page).toHaveTitle('Example Domain');
await context.close();
});
}
Capture screenshots on failures and generate traces to debug your tests.
test('Verify page title with screenshot', async ({ page }, testInfo) => {
try {
await page.goto('https://www.example.com');
await expect(page).toHaveTitle('Example Domain');
} catch (error) {
await page.screenshot({ path: `screenshots/${testInfo.title}.png` });
throw error;
}
});
Playwright can also perform API testing, making it a versatile tool for full-stack testing.
test('API test', async ({ request }) => {
const response = await request.get('https://api.example.com/data');
expect(response.status()).toBe(200);
const data = await response.json();
expect(data).toHaveProperty('key');
});
beforeAll
, beforeEach
, afterAll
, and afterEach
to set up and tear down tests.Playwright tests can be integrated into CI tools like Jenkins, GitHub Actions, or Travis CI to automate testing workflows.
Create a .github/workflows/playwright.yml
file:
name: Playwright Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install dependencies
run: npm install
- name: Run Playwright tests
run: npm run test
Playwright is a powerful and versatile tool that simplifies automated web testing across all modern browsers. Its robust feature set, ease of use, and active development community make it an excellent choice for any software engineer looking to enhance their testing capabilities.
By adopting Playwright, you can write more reliable tests, reduce maintenance overhead, and deliver high-quality web applications that meet user expectations.
Ready to Level Up Your Testing?
Start integrating Playwright into your workflow today and experience the difference it can make in your development process.
About Me
Since I was a child, I've always wanted to be an inventor. As I grew up, I specialized in information systems, an area which I fell in love with and live around it. I am a full-stack developer and work a lot with devops, i.e., I'm a kind of "jack-of-all-trades" in IT. Wherever there is something cool or new, you'll find me exploring and learning... I am passionate about life, family, and sports. I believe that true happiness can only be achieved by balancing these pillars. I am always looking for new challenges and learning opportunities, and would love to connect with other technology professionals to explore possibilities for collaboration. If you are looking for a dedicated and committed full-stack developer with a passion for excellence, please feel free to contact me. It would be a pleasure to talk with you! |
SecurityScoreCard
Nov. 2023 - Present
New York, United States
Senior Software Engineer
I joined SecurityScorecard, a leading organization with over 400 employees, as a Senior Full Stack Software Engineer. My role spans across developing new systems, maintaining and refactoring legacy solutions, and ensuring they meet the company's high standards of performance, scalability, and reliability.
I work across the entire stack, contributing to both frontend and backend development while also collaborating directly on infrastructure-related tasks, leveraging cloud computing technologies to optimize and scale our systems. This broad scope of responsibilities allows me to ensure seamless integration between user-facing applications and underlying systems architecture.
Additionally, I collaborate closely with diverse teams across the organization, aligning technical implementation with strategic business objectives. Through my work, I aim to deliver innovative and robust solutions that enhance SecurityScorecard's offerings and support its mission to provide world-class cybersecurity insights.
Technologies Used:
Node.js Terraform React Typescript AWS Playwright and Cypress