Playwright TypeScript Real World Project: Step-by-Step Guide (2026) | TechSarvam

1. Introduction to a Real-World Playwright TypeScript Project

Learning Playwright commands is important, but real QA Automation Engineer and SDET roles require more than writing individual test scripts. Companies expect engineers to create maintainable automation frameworks, manage test data, validate APIs, investigate failures, and integrate tests into CI/CD pipelines.

A Playwright TypeScript real world project gives you an opportunity to practise these skills using one practical application.

In this tutorial, we will build an e-commerce automation framework. It will cover login, product search, shopping cart, and checkout workflows using Playwright Test and TypeScript.

You will also learn how to use the Page Object Model (POM), reusable fixtures, environment variables, API testing, browser projects, and HTML reporting.

The examples are designed for beginners, Selenium testers transitioning to Playwright, QA Automation Engineers, and SDETs.

2. Project Overview, Business Requirements, and Testing Scope

Project overview

Imagine an online shopping application where customers can:

  1. Log in using their account.
  2. Search and view products.
  3. Add products to the shopping cart.
  4. Update cart quantities.
  5. Enter checkout information.
  6. Place an order and view confirmation.

Our goal is to automate these business workflows and verify that important application features work correctly.

Demo application assumptions: The examples use a demo e-commerce application with predictable test IDs and an API contract described below. You must replace the base URL, selectors, and API paths with those supported by your chosen demo application. No production credentials or live execution results are assumed.

Testing scope

ModuleTest scenarios
LoginValid login, invalid password, empty fields
Product searchSearch existing and unavailable products
CartAdd item, remove item, verify quantity
CheckoutValid checkout, missing information, order confirmation
APIProduct response and status validation
RegressionRecheck important customer workflows

We will include positive, negative, regression, and end-to-end test scenarios.

3. Prerequisites and Environment Setup

Install the following before starting:

Create a project:

mkdir ecommerce-playwright

cd ecommerce-playwright

npm init -y

Install Playwright:

npm install -D @playwright/test typescript @types/node

npx playwright install

Create a TypeScript configuration:

{

  “compilerOptions”: {

    “target”: “ES2022”,

    “module”: “commonjs”,

    “strict”: true,

    “esModuleInterop”: true,

    “types”: [“node”, “@playwright/test”]

  }

}

For additional setup instructions, refer to our Playwright TypeScript Setup Guide.

4. Creating the Project and Folder Structure

A good automation framework separates test cases, page objects, test data, fixtures, and configuration.

Create the following structure:

ecommerce-playwright/

│

├── tests/

│   ├── login.spec.ts

│   ├── search.spec.ts

│   ├── cart.spec.ts

│   ├── checkout.spec.ts

│   └── api.spec.ts

│

├── pages/

│   ├── LoginPage.ts

│   ├── ProductsPage.ts

│   ├── CartPage.ts

│   └── CheckoutPage.ts

│

├── fixtures/

│   └── test-fixtures.ts

│

├── test-data/

│   └── products.json

│

├── utils/

│   └── environment.ts

│

├── .github/

│   └── workflows/

│       └── playwright.yml

│

├── playwright.config.ts

├── package.json

├── tsconfig.json

└── .gitignore

This structure makes the Playwright TypeScript project easier to maintain as the number of tests increases.

For a deeper explanation, read Playwright TypeScript Project Structure and Playwright Framework Design.

5. Configuring playwright.config.ts for Multiple Browsers and Environments

Playwright supports Chromium, Firefox, and WebKit. You can define browser projects and run the same tests across multiple engines.

Create playwright.config.ts:

import { defineConfig, devices } from ‘@playwright/test’;

const baseURL =

  process.env.BASE_URL || ‘https://your-demo-shop.example’;

export default defineConfig({

  testDir: ‘./tests’,

  fullyParallel: true,

  forbidOnly: !!process.env.CI,

  retries: process.env.CI ? 2 : 0,

  workers: process.env.CI ? 2 : undefined,

  reporter: [

    [‘list’],

    [‘html’, { open: ‘never’ }]

  ],

  use: {

    baseURL,

    screenshot: ‘only-on-failure’,

    video: ‘retain-on-failure’,

    trace: ‘retain-on-failure’

  },

  projects: [

    {

      name: ‘chromium’,

      use: { …devices[‘Desktop Chrome’] }

    },

    {

      name: ‘firefox’,

      use: { …devices[‘Desktop Firefox’] }

    },

    {

      name: ‘webkit’,

      use: { …devices[‘Desktop Safari’] }

    }

  ]

});

Replace the example base URL with your demo application’s actual address.

The configuration provides:

For more details, read Playwright TypeScript Test Configuration and Playwright TypeScript Multi-Browser Config.

6. Implementing Page Object Model and Reusable Fixtures

The Page Object Model separates page-specific actions from test scenarios.

For example, instead of writing login locators in every test, create one LoginPage class.

LoginPage.ts

import { Page, expect } from ‘@playwright/test’;

export class LoginPage {

  constructor(private page: Page) {}

  async open() {

    await this.page.goto(‘/login’);

  }

  async login(username: string, password: string) {

    await this.page.getByTestId(‘username’).fill(username);

    await this.page.getByTestId(‘password’).fill(password);

    await this.page.getByTestId(‘login-button’).click();

  }

  async verifyLoginSuccess() {

    await expect(

      this.page.getByTestId(‘account-menu’)

    ).toBeVisible();

  }

  async verifyLoginError() {

    await expect(

      this.page.getByTestId(‘login-error’)

    ).toBeVisible();

  }

}

These test IDs are assumptions for the demo application. Use the actual accessible roles, labels, or test IDs provided by your application.

ProductsPage.ts

import { Page, expect } from ‘@playwright/test’;

export class ProductsPage {

  constructor(private page: Page) {}

  async searchProduct(name: string) {

    await this.page.getByTestId(‘search-input’).fill(name);

    await this.page.getByTestId(‘search-button’).click();

  }

  async addToCart(productId: string) {

    await this.page

      .getByTestId(`add-to-cart-${productId}`)

      .click();

  }

  async verifyProduct(name: string) {

    await expect(

      this.page.getByText(name, { exact: true })

    ).toBeVisible();

  }

}

Creating reusable fixtures

Fixtures allow you to initialize page objects once and share them across tests.

Create fixtures/test-fixtures.ts:

import { test as base } from ‘@playwright/test’;

import { LoginPage } from ‘../pages/LoginPage’;

import { ProductsPage } from ‘../pages/ProductsPage’;

type AppFixtures = {

  loginPage: LoginPage;

  productsPage: ProductsPage;

};

export const test = base.extend<AppFixtures>({

  loginPage: async ({ page }, use) => {

    await use(new LoginPage(page));

  },

  productsPage: async ({ page }, use) => {

    await use(new ProductsPage(page));

  }

});

export { expect } from ‘@playwright/test’;

Now tests can import the custom test object and access reusable page objects.

Explore Playwright TypeScript Page Object Model and Playwright TypeScript Fixtures for more advanced examples.

7. Creating Tests for Login, Product Search, Cart, and Checkout

Let’s implement the main business scenarios.

Login test

Create tests/login.spec.ts:

import { test, expect } from ‘../fixtures/test-fixtures’;

test(‘customer can log in’, async ({ loginPage, page }) => {

  await loginPage.open();

  await loginPage.login(

    process.env.TEST_USERNAME!,

    process.env.TEST_PASSWORD!

  );

  await loginPage.verifyLoginSuccess();

  await expect(page).toHaveURL(/account/);

});

test(‘customer cannot log in with invalid password’, async ({

  loginPage

}) => {

  await loginPage.open();

  await loginPage.login(‘invalid-user’, ‘wrong-password’);

  await loginPage.verifyLoginError();

});

The first test checks a positive login scenario. The second checks negative authentication behaviour.

The demo application must provide the matching account and error behaviour.

Product search test

Create tests/search.spec.ts:

import { test } from ‘../fixtures/test-fixtures’;

test(‘customer can search for a product’, async ({

  page,

  productsPage

}) => {

  await page.goto(‘/products’);

  await productsPage.searchProduct(‘Laptop’);

  await productsPage.verifyProduct(‘Laptop’);

});

You can add another negative test to verify that an unavailable search term displays an appropriate empty-state message.

Cart and checkout workflow

Create page objects for cart and checkout actions using the same pattern.

For example, CartPage.ts:

import { Page, expect } from ‘@playwright/test’;

export class CartPage {

  constructor(private page: Page) {}

  async open() {

    await this.page.goto(‘/cart’);

  }

  async verifyItem(name: string) {

    await expect(

      this.page.getByText(name, { exact: true })

    ).toBeVisible();

  }

  async removeItem() {

    await this.page.getByTestId(‘remove-item’).click();

  }

}

Create CheckoutPage.ts:

import { Page, expect } from ‘@playwright/test’;

export class CheckoutPage {

  constructor(private page: Page) {}

  async enterDetails(

    firstName: string,

    lastName: string,

    postalCode: string

  ) {

    await this.page.getByTestId(‘first-name’).fill(firstName);

    await this.page.getByTestId(‘last-name’).fill(lastName);

    await this.page.getByTestId(‘postal-code’).fill(postalCode);

  }

  async placeOrder() {

    await this.page.getByTestId(‘place-order’).click();

  }

  async verifyConfirmation() {

    await expect(

      this.page.getByTestId(‘order-confirmation’)

    ).toBeVisible();

  }

}

A checkout test can now combine these reusable actions:

import { test } from ‘@playwright/test’;

import { CartPage } from ‘../pages/CartPage’;

import { CheckoutPage } from ‘../pages/CheckoutPage’;

test(‘customer completes checkout’, async ({ page }) => {

  const cart = new CartPage(page);

  const checkout = new CheckoutPage(page);

  await cart.open();

  await cart.verifyItem(‘Laptop’);

  await page.getByTestId(‘checkout-button’).click();

  await checkout.enterDetails(

    ‘Test’,

    ‘Customer’,

    ‘560001’

  );

  await checkout.placeOrder();

  await checkout.verifyConfirmation();

});

This example assumes that the cart already contains the Laptop product. In a fully isolated test, add the product through the UI or prepare the cart using a supported API setup before starting checkout.

8. Managing Test Data, Environment Variables, and Authentication

Avoid hardcoding environment-specific values in test files.

Create a .env file for local execution:

BASE_URL=https://your-demo-shop.example

TEST_USERNAME=your-demo-username

TEST_PASSWORD=your-demo-password

Install dotenv:

npm install -D dotenv

Load the environment file at the beginning of playwright.config.ts:

import dotenv from ‘dotenv’;

dotenv.config();

Add .env to .gitignore:

node_modules/

.env

playwright-report/

test-results/

playwright/.auth/

Use CI secrets for credentials in GitHub Actions or Jenkins rather than committing passwords to the repository.

You can also store reusable product data in test-data/products.json:

[

  {

    “id”: “laptop-101”,

    “name”: “Laptop”,

    “category”: “Electronics”

  },

  {

    “id”: “phone-102”,

    “name”: “Mobile Phone”,

    “category”: “Electronics”

  }

]

Authentication can be improved by using Playwright storage state when appropriate. Create an authenticated state in a setup project and reuse it for tests that require the same user session. Keep authentication files out of source control because they may contain reusable session credentials.

Read Playwright TypeScript Authentication Setup for a complete authentication workflow.

9. Adding API Testing, Assertions, Screenshots, Traces, and HTML Reports

Real-world QA automation should validate both UI behaviour and API responses.

Playwright provides an API request fixture for API testing.

Create tests/api.spec.ts:

import { test, expect } from ‘@playwright/test’;

test(‘product API returns product details’, async ({ request }) => {

  const response = await request.get(

    `${process.env.BASE_URL}/api/products`

  );

  expect(response.status()).toBe(200);

  const products = await response.json();

  expect(Array.isArray(products)).toBeTruthy();

});

This example assumes the demo application exposes GET /api/products and returns a JSON array. Change the endpoint and expected response to match the actual API contract.

Playwright’s web-first assertions automatically retry until the expected condition is met or the timeout expires:

await expect(

  page.getByTestId(‘order-confirmation’)

).toBeVisible();

The configuration also captures useful failure evidence:

Generate the HTML report:

npx playwright test

npx playwright show-report

This gives QA engineers a convenient way to investigate failed regression tests.

For further learning, explore Playwright API Testing, Playwright TypeScript Reporting, and Playwright TypeScript Debugging Tips.

10. Running Tests in Parallel and Integrating CI/CD

Playwright supports parallel execution through workers. The fullyParallel and workers configuration options help control how tests run.

Run the full suite:

npx playwright test

Run one test file:

npx playwright test tests/login.spec.ts

Run only Chromium:

npx playwright test –project=chromium

GitHub Actions integration

Create .github/workflows/playwright.yml:

name: E-commerce Playwright Tests

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – uses: actions/checkout@v4

      – uses: actions/setup-node@v4

        with:

          node-version: 22

          cache: npm

      – name: Install dependencies

        run: npm ci

      – name: Install browsers

        run: npx playwright install –with-deps

      – name: Run tests

        run: npx playwright test

        env:

          BASE_URL: ${{ secrets.BASE_URL }}

          TEST_USERNAME: ${{ secrets.TEST_USERNAME }}

          TEST_PASSWORD: ${{ secrets.TEST_PASSWORD }}

      – name: Upload test reports

        if: ${{ !cancelled() }}

        uses: actions/upload-artifact@v4

        with:

          name: playwright-report

          path: |

            playwright-report/

            test-results/

          retention-days: 14

Configure the three secrets in your GitHub repository before running this workflow. The demo application must also be accessible from the CI runner.

For Jenkins, use a pipeline with stages for checkout, dependency installation, browser installation, and test execution. Archive playwright-report/** and test-results/** in a post { always { … } } block so reports remain available after failed test runs.

Read Playwright TypeScript CI/CD Pipeline and Playwright TypeScript Parallel Testing for additional implementation guidance.

11. Troubleshooting and Best Practices

Problem: Tests fail because an element cannot be located.

Use Playwright Inspector and verify that the locator matches the actual application. Prefer accessible roles, labels, and stable test IDs over fragile XPath expressions.

Problem: Tests pass locally but fail in CI.

Check browser dependencies, environment variables, application availability, and test data. Use traces to investigate timing and navigation problems.

Problem: Tests fail when executed in parallel.

Check whether tests share accounts, modify the same records, or depend on execution order. Use isolated test data and independent browser contexts.

Problem: Checkout tests produce inconsistent results.

Avoid depending on data created by another test. Each test should prepare its own required state and clean up data where possible.

Best practices

12. Frequently Asked Questions

1. What are the benefits of Playwright TypeScript real world project?

It provides practical experience in browser automation, Page Object Model, fixtures, API testing, test data management, cross-browser execution, reporting, and CI/CD. These skills are useful for QA Automation Engineer and SDET roles.

2. How do I get started with Playwright TypeScript real world project?

Install Node.js and Playwright Test, create a TypeScript project, configure playwright.config.ts, and select a demo application. Start with login and product search before implementing cart, checkout, API tests, and CI/CD.

3. Is Playwright TypeScript real world project suitable for beginners?

Yes. Beginners can build the framework step by step. Start with basic locators and assertions, then learn page objects, fixtures, environment configuration, and advanced reporting.

4. Which design pattern is commonly used in Playwright automation frameworks?

The Page Object Model is commonly used to separate page interactions from test logic. Fixtures can provide reusable page objects and setup steps.

5. Can Playwright run tests on multiple browsers?

Yes. Playwright supports Chromium, Firefox, and WebKit through browser projects in its configuration.

Leave a Comment

Your email address will not be published. Required fields are marked *