vasu31dev / playwright-ts-template

Playwright Typescript Automation testing framework Template is designed for Web (Desktop & Mobile), API, and Electron apps. Stable and Robust layer on top of Playwright with inbuilt Utilities, Linting, Logger, Web hooks, Github actions, Reports and much more
112 stars 5 forks source link
allure-report api-automation-testing browser-testing ci-cd-pipeline e2e-testing electron-app end-to-end-testing github-actions mobile-web playwright qa-automation template test-framework typescript ui-test-automation web-testing

GitHub stars Last Commit Pull Requests npm version Release Notes


# 🚀 Elevate Your Automation: Redefining the Future of Testing, Where Precision Meets Efficiency. ## Playwright TypeScript Framework: "Your One-Stop Solution for Web (Desktop & Mobile), API, and Electron Automation Testing"

Welcome to the Playwright TypeScript Framework. This unique and comprehensive automation framework is designed to simplify and streamline the process of writing and managing automated tests for Web (Desktop & Mobile), APIs, and Electron Desktop applications. It's built on Playwright, a powerful browser automation library, and TypeScript, a statically typed superset of JavaScript, offering a robust and efficient environment for end-to-end testing.

This framework is ideal for QA professionals, developers, and business analysts looking to improve their testing practices and efficiency. It's equipped with utilities that simplify test creation and maintenance, allowing you to focus on writing your tests out of the box.

Key Features:

In summary, the Playwright TypeScript Framework is a powerful, flexible, and user-friendly tool that leverages the power of Playwright and TypeScript. It's an excellent choice for teams looking to improve their testing practices and efficiency.

Table of Contents

Getting Started

Tools & Frameworks

Prerequisites

Before you begin, there are some essential requirements you must meet. Ensure you have the following software installed on your machine:

Installation

Begin your project by following the steps to install it either with command-line instructions or by doing it step-by-step manually.

CLI Installation

This method makes setup easy by avoiding the long steps in the manual installation process. It automatically installs all the dependencies, libraries, playwright browsers, Winston logger, and Husky pre-commit hook that are necessary to start your project. Initializing the project, also intitialises a new Git repository if neither the current nor the parent directory is a Git repository.

The installation steps are below:

  1. Install Node.js

    Node.js installation can be done directly from the website or through CLI. Find the Node.js installation steps here.

  2. Create a Playwright Test Directory

    mkdir playwright-e2e-tests
    cd playwright-e2e-tests
  3. Run the below command to initialize a project

    npx vasu-playwright-cli init

    This command will set up a new project with a ready-to-use Playwright TypeScript framework, which includes:

    • Setting up the Playwright TypeScript framework template with sample tests.
    • Creating a new package.json file with all the necessary dependencies.
    • Initializing a new Git repository if neither the current nor parent directory is a Git repository.
    • Installing all the npm packages, including the playwright utils library, which contains playwright helper methods.
  4. If you encounter errors during the installation process, follow these steps to resolve them:

    • Change ownership of the npm directories to the current user:

      sudo chown -R $(whoami) ~/.npm
    • Clear the npm cache forcefully:

      npm cache clean --force
    • Retry initializing the Playwright TypeScript project:

      npx vasu-playwright-cli init

    These steps will help fix permission issues and cache-related problems that might occur during the setup.

Manual Installation

This is a step-by-step process to install all the dependencies, libraries, and playwright browsers manually. Please refer to the Installation section for complete instructions on setting up the project on your local machine.

Project Update Guide

Keeping your project up to date is crucial.

Update Playwright library

Project Structure

Understanding the project's architecture is key to working with the code. Please refer to the Project Structure section for an overview of the directory layout and file organization.

Customize Framework Setup

Learn how to configure and customize the framework to suit your needs. Please refer to the Customize Framework Setup section for detailed instructions.

Page Context set up

Setting up a page context is a common task in web testing. Please refer to the Pages section on how to set up a page context before each test.

Usage

Page Objects

Page objects are utilized to encapsulate information about the elements present on each page of your application. They also provide a structured way to write action and assertion functions for various functionalities on each page. This approach promotes code reusability and makes the tests easier to maintain and understand. Page objects can be found in the pages directory.

Here's an example of a page object under the pages package:

sauce-demo-login-page.ts

// importing test data
// @testdata is the alias path set to testdata directory in tsconfig.json file
import { failureLoginCredentials, sauceDemoCredentials } from '@testdata/sauce-demo-test-data';

// importing utility functions
import { click, clickAndNavigate, fill, gotoURL } from 'vasu-playwright-utils';
import { expectElementToBeVisible } from 'vasu-playwright-utils';
import { getLocator, getLocatorByPlaceholder, getLocatorByRole } from 'vasu-playwright-utils';

const userName = `#user-name`;
const password = () => getLocator(`#password`).or(getLocatorByPlaceholder('Password', { exact: true }));
const login = () => getLocatorByRole('button', { name: 'Login' });
const errorMessage = `//*[contains(@class,'error-message')]`;

export async function navigateToSauceDemoLoginPage() {
  await gotoURL('https://www.saucedemo.com/');
}

export async function logInSuccessfully() {
  await fill(userName, successLoginCredentials.username);
  await fill(password(), successLoginCredentials.password);
  await clickAndNavigate(login());
}

export async function failureLogin() {
  await fill(userName, failureLoginCredentials.username);
  await fill(password(), failureLoginCredentials.password);
  await click(login());
}

export async function verifyErrorMessageForFailureLogin() {
  await expectElementToBeVisible(errorMessage);
}

export async function verifyLoginPageisDisplayed() {
  await expectElementToBeVisible(userName);
}

In this example, the sauce-demo-login-page represents the login page within the application. It includes methods to navigate to the Saucedemo homepage, execute both successful and unsuccessful login actions, verify the success of the login in the successful login scenario, and confirm the display of an error message in the case of a failed login.

Refer to the Utilities section on how to import and use utility functions.

Refer to the Running Tests section below on how to run tests.

Writing Tests in a spec file

Tests are written in the specs directory. Each test file should correspond to a specific feature or functionality of the application under test. Tests are constructed using Page objects.

Here's an example of a test file under the specs directory:

sauce-demo-all-pass.spec.ts

// import test from PageSetup.ts which sets up the page before each test
// @pagesetup is the alias path set up to page-setup.ts in tsconfig.json file
import { test } from '@pagesetup';

// importing page objects to use all functions within that page to construct the tests
// @pages is the alias path set up to pages directory in tsconfig.json file
import * as LoginPage from '@pages/sauce-demo/sauce-demo-login-page';
import * as MiniCart from '@pages/sauce-demo/sauce-demo-mini-cart';
import * as ProductsPage from '@pages/sauce-demo/sauce-demo-products-page';

test.describe.configure({ mode: 'parallel' });

test.describe('Saucedemo tests for successful, unsuccessful logins and add products to cart @smoke', () => {
  // beforEach hook to navigate to home page in each test
  test.beforeEach('Navigating to sauce demo page', async () => {
    await LoginPage.navigateToSauceDemoLoginPage();
  });

  test('Saucedemo tests - Successful login will display Products Page', async () => {
    await LoginPage.loginWithValidCredentials();
    // verifying products page is displayed on successful login
    await ProductsPage.verifyProductsPageIsDisplayed();
  });

  test('Saucedemo test - Error message is displayed and Products page is not displayed on failed login', async () => {
    await LoginPage.loginWithInvalidCredentials();
    // verifying Login is still displayed
    await LoginPage.verifyLoginPageisDisplayed();
    // verifying Products Page is not displayed
    await ProductsPage.verifyProductsPageIsNotDisplayed();
  });

  test('Saucedemo test - Add product to cart', async () => {
    await LoginPage.loginWithValidCredentials();
    await ProductsPage.verifyProductsPageIsDisplayed();
    await ProductsPage.addToCartByProductNumber(1);
    // verifying mini cart count is updated to 1
    await MiniCart.verifyMiniCartCount('1');
  });
});

In this example, we are setting the page state by importing test from @PageSetup and writing the spec file. Here are some important points to note:

  1. Import test from @PageSetup instead from @playwright/test. page-setup is customized for this framework to set the page state. This ensures that the page is set up correctly before each test.

  2. setPage function from page-setup file will set the page state before each test and is imported to our spec files while executing the tests. If you want to use the Playwright page directly to write our tests, we can use getPage function from page-utils file. The page object is managed by the framework, and we can use the setPage and getPage functions to set and get the page state, ensuring that all of the pages operate on the same page object.

In the first test.describe block of this example, We first navigate to the home page, then perform the login action, and finally verify if the login was successful. Here LoginPage represents a login page within the application. It includes methods to navigate to the homepage, perform a login action, and assertions for successful and failed logins.

Similarly, ProductsPage and MiniCart are also page objects that have functions for their respective pages. Here,ProductsPage page functions are used to assert whether products page is displayed on successful login and also adding products to cart. MiniCart page function is used to verify the cart count after adding products to cart.

The beforeEach hook, is utilized to navigate to the home page before the execution of each test within the test.describe block in this file.

Parameterising Tests

Test and Project parameterization

Playwright supports parameterization both at test level and project level. Sample parameterized test spec file was added as sauce-demo-parameterised.spec.ts under specs folder for easy reference. For project-level parameterisation, please refer to the Playwright documentation here.

Passing environment variables

You can pass environment variables to Playwright test scripts to configure and customize their behavior. These variables are useful for storing sensitive information like API keys and configuring test parameters based on the environment. You can set and use these variables in various ways, from the command line to test configurations. For more information on how to set and use these variables, please refer to the Playwright documentation here.

Test data from CSV file

For a data-driven approach, Playwright supports creating tests from CSV files. For more information, please refer to the Playwright documentationhere.

Utilities

Explore various utility functions and helpers that can make your testing more efficient. The Utilities section in this project encompasses a variety of functions designed to enhance the efficiency of your testing process. These utilities include:

  1. Page Utilities: Functions that assist in setting and getting page objects, switching between the pages, closing and reloding a page, loading and getting the page url, getting windows size, page navigations etc.
  2. Locator Utilities: Functions that assist in locating elements on the page, making it easier to interact with them.
  3. Action Utilities: Functions that encapsulate standard actions such as clicking, form filling, keyboard events, and dragging; providing a more concise way to execute these operations within your tests.
  4. Element Utilities: Functions for handling conditional statements with web elements, such as checking if an element is visible, hidden, or contains certain text or input values.
  5. Assertion Utilities: Helpers that simplify the process of making assertions about the state of the application, enhancing the readability and maintainability of your tests.
  6. Optional Parameter Type Objects: Provides a set of options for utility modules.

Please refer to the Utilities documentation for a comprehensive guide to the available utilities in this project, including detailed descriptions and examples of how to import and use them.

Executing Tests

We have the flexibility from executing a single test to executing a specific set of tests, or the entire test suite. Testing can be carried out on a single browser or across multiple browsers simultaneously. By default, tests run in a headless mode, and the test outcome is displayed in the terminal.

Run tests using Playwright Test for VSCode Extension

Playwright Test for VSCode extension empowers you to run specific tests or entire test suites directly from the editor. You can conveniently trigger tests with a click, making it efficient to validate changes.

For detailed guidance on configuring test settings in the playwright.config file, and executing tests, please visit Executing tests using a Playwright Test for VSCode extension.

Parallel Execution

Playwright allows you to execute tests in parallel across multiple workers. This can significantly speed up the execution of your test suite.

To enable parallel execution, add the following line at the top of your spec file, above the test block:

test.describe.configure({ mode: 'parallel' });

The number of workers can be configured either in the playwright.config file or via the command-line interface.

Running Tests via the Command-Line Interface

Utilize a variety of commands to execute your tests in different modes. Below are a few illustrative examples:

npm run commands

The package.json file contains several scripts designed to streamline test execution. Here are a few common examples:

npm run test:chromium-headed -- -g 'Successful login will display Products Page'
npm run test:chromium -- sauce-demo-all-pass.spec.ts
npm run test:chromium-headed -- sauce-demo-parameterised.spec.ts sauce-demo-all-pass.spec.ts
npm run test:chromium -- sauce-demo-all-pass.spec.ts -j 3 --retries 2
npm run test:chromium-headed -- -g 'Saucedemo test - Add product to cart' --debug
npm run test -- -g '@smoke'
npm run test

npx playwright test commands

You can also use the playwright command to run your tests as illustrated in the below example:

npx playwright test -c playwright.config.ts -g "logo is present @reg" --headed -j 1 --retries 0

Here's what each option does:

CLI Parallel Execution

For more information, please refer to the Playwright CLI documentation.

Report Generation and Viewing

Playwright Test offers several built-in reporters tailored for various requirements, while also offering the flexibility to seamlessly integrate custom reporters. You can configure these reporters either through the command line or within the playwright.config.ts file. For a comprehensive guide on Playwright's in-built reporters, refer to the official documentation.

Accessing Reports via Command-Line Interface (CLI)

npx playwright show-report <path to the report>
"report": "playwright show-report playwright-report"

To access the reports post-test execution using this configuration, run:

npm run report

Additional Playwright Features

Best Practices

Here are some recommended best practices when using this framework:

In addition to these, Playwright also recommends following certain best practices. You can find more details in the Playwright Best Practices documentation

FAQs

Please refer to the FAQ documentation for questions about dependencies, libraries, utilities and errors.

Issues and Feedback

If you encounter any issues or have feedback, please Raise an Issue on GitHub.

Contributions

We welcome contributions! Feel free to submit a Pull Request on GitHub.