Playwright TypeScript Custom Reporter: Step-by-Step Guide (2026) | TechSarvam

1. Introduction to Custom Reporting in Playwright TypeScript

Playwright provides built-in reporters that display test execution results in different formats. However, some automation projects require additional reporting information, such as business module names, execution duration, failed test details, retry counts, and customized summaries.

This is where a Playwright TypeScript custom reporter becomes useful.

A custom reporter allows QA Automation Engineers and SDETs to control how test execution results are collected, processed, and displayed.

For example, consider an e-commerce automation framework containing 200 regression test cases. The QA team may want a report showing:

Instead of depending only on the default Playwright report, you can develop your own reporting class using TypeScript.

In this tutorial, we will create a working custom reporter that generates JSON and CSV reports while using Playwright’s built-in HTML reporter.

2. What Is a Playwright Reporter and Why Create a Custom One?

A Playwright reporter is a component that receives notifications from the Playwright test runner during test execution.

It collects information about test execution and produces reports.

Playwright provides several built-in reporters:

ReporterPurpose
ListDisplays individual test results
LineShows compact execution updates
DotDisplays test results using dots
HTMLGenerates an interactive HTML report
JSONProduces structured test results
JUnitGenerates XML reports for CI tools
GitHubProvides GitHub Actions annotations

Why Create a Custom Reporter?

A custom reporter is useful when default reporting does not meet project requirements.

For example:

  • A QA manager needs a customized regression summary.
  • A client requires CSV execution reports.
  • A team wants to track flaky tests.
  • An organization needs module-wise test statistics.
  • A CI/CD pipeline requires custom execution metrics.

Custom reporting helps make automation results more useful for developers, testers, and management teams.

3. Understand the Playwright Reporter API and Lifecycle Methods

Playwright provides a Reporter API that allows developers to create custom reporting classes.

A reporter implements selected lifecycle methods.

The most important methods are:

MethodPurpose
onBegin()Executes before test execution starts
onTestBegin()Executes when an individual test starts
onTestEnd()Executes when an individual test finishes
onEnd()Executes after the test run completes
onError()Handles errors outside normal test execution
onStepBegin()Executes when a test step starts
onStepEnd()Executes when a test step finishes

Understand the Reporter Lifecycle

1. onBegin()

Called once before the test execution begins. It provides the resolved configuration and discovered test suite.

2. onTestBegin()

Called whenever a test starts executing.

3. onTestEnd()

Called after a test finishes. It provides the final result, including status, duration, retry information, and errors.

4. onEnd()

Called after the test run finishes. It is useful for generating final reports and execution summaries.

These methods provide the foundation for implementing Playwright custom reporting.

4. Project Setup and Prerequisites

Before starting the Playwright TypeScript custom reporter tutorial, install:

  • Node.js
  • npm
  • Visual Studio Code
  • Playwright
  • TypeScript

Create a project:

mkdir playwright-custom-reporter

cd playwright-custom-reporter

Initialize Playwright:

npm init playwright@latest

Select TypeScript when prompted.

Install the required dependencies:

npm install -D @playwright/test typescript

Verify Playwright:

npx playwright –version

Recommended Project Structure

playwright-custom-reporter/

│

├── tests/

│   ├── login.spec.ts

│   └── homepage.spec.ts

│

├── reporters/

│   └── customReporter.ts

│

├── reports/

│

├── playwright.config.ts

├── package.json

├── package-lock.json

├── tsconfig.json

└── .gitignore

The reporters folder contains custom reporting logic, while the reports folder stores generated execution reports.

5. Create a Custom Reporter Class Using TypeScript

Now let’s create a custom reporter using the Playwright Reporter API.

Create a file:

reporters/customReporter.ts

Import the required interfaces:

import type {

  Reporter,

  FullConfig,

  FullResult,

  Suite,

  TestCase,

  TestResult

} from ‘@playwright/test/reporter’;

export default class CustomReporter implements Reporter {

  onBegin(config: FullConfig, suite: Suite) {

    console.log(‘Starting Playwright execution’);

    console.log(

      `Total tests: ${suite.allTests().length}`

    );

  }

  onTestEnd(test: TestCase, result: TestResult) {

    console.log(

      `${test.title} – ${result.status}`

    );

  }

  onEnd(result: FullResult) {

    console.log(

      `Execution completed: ${result.status}`

    );

  }

}

Explanation

  • Reporter defines the reporter interface.
  • FullConfig contains resolved Playwright configuration.
  • Suite represents the test hierarchy.
  • TestCase provides test information.
  • TestResult contains execution results.
  • FullResult provides the final execution status.

The class implements the Reporter interface and exports the reporter as its default export.

This is the basic structure of a Playwright TypeScript custom reporter.

6. Implement onBegin, onTestEnd, and onEnd Methods

Let’s understand how to use these methods in a practical scenario.

A. Implement onBegin()

The onBegin() method runs before test execution.

onBegin(config: FullConfig, suite: Suite) {

  const totalTests = suite.allTests().length;

  console.log(‘Execution Started’);

  console.log(`Total Tests: ${totalTests}`);

  console.log(`Workers: ${config.workers}`);

}

This method collects the total number of discovered tests and configured workers.

B. Implement onTestEnd()

The onTestEnd() method captures individual test results.

onTestEnd(test: TestCase, result: TestResult) {

  console.log(`Test Name: ${test.title}`);

  console.log(`Status: ${result.status}`);

  console.log(`Duration: ${result.duration} ms`);

  console.log(`Retry: ${result.retry}`);

  if (result.error) {

    console.log(`Error: ${result.error.message}`);

  }

}

This information helps identify which automated test failed and how long it took to execute.

C. Implement onEnd()

The onEnd() method executes after all tests finish.

onEnd(result: FullResult) {

  console.log(‘Test Execution Completed’);

  console.log(`Final Status: ${result.status}`);

  console.log(`Total Duration: ${result.duration} ms`);

}

You can use this method to generate JSON, CSV, or other custom reports.

7. Capture Test Status, Duration, Errors, and Execution Summaries

A useful custom reporter should capture more than just passed and failed statuses.

It should collect:

  • Test name.
  • Test file.
  • Project name.
  • Execution status.
  • Duration.
  • Retry count.
  • Error message.

Playwright also allows you to identify flaky tests.

A test that initially fails but passes after a retry is considered flaky. In our example, we can identify this using:

const isFlaky =

  result.status === ‘passed’ &&

  result.retry > 0;

This is useful for tracking unstable automated test scripts.

Example Execution Summary

Playwright Custom Test Report

Total Tests: 20

Passed: 15

Failed: 2

Skipped: 1

Flaky: 2

Execution Status: Failed

Duration: 45000 ms

These metrics help QA teams understand the quality of the regression test execution.

8. Generate Custom JSON and CSV Reports

Now let’s build a complete reporter that saves test execution information into JSON and CSV files.

Update reporters/customReporter.ts:

import {

  mkdirSync,

  writeFileSync

} from ‘node:fs’;

import type {

  Reporter,

  FullConfig,

  FullResult,

  Suite,

  TestCase,

  TestResult

} from ‘@playwright/test/reporter’;

interface TestRecord {

  title: string;

  file: string;

  project: string;

  status: string;

  duration: number;

  retry: number;

  flaky: boolean;

  error?: string;

}

export default class CustomReporter implements Reporter {

  private records: TestRecord[] = [];

  onBegin(config: FullConfig, suite: Suite) {

    console.log(‘Playwright execution started’);

    console.log(

      `Discovered Tests: ${suite.allTests().length}`

    );

  }

  onTestEnd(test: TestCase, result: TestResult) {

    const record: TestRecord = {

      title: test.title,

      file: test.location.file,

      project: test.parent.project()?.name || ‘default’,

      status: result.status,

      duration: result.duration,

      retry: result.retry,

      flaky:

        result.status === ‘passed’ &&

        result.retry > 0,

      error: result.error?.message

    };

    this.records.push(record);

  }

  onEnd(result: FullResult) {

    mkdirSync(‘reports’, { recursive: true });

    const passed = this.records.filter(

      r => r.status === ‘passed’ && !r.flaky

    ).length;

    const failed = this.records.filter(

      r => r.status === ‘failed’

    ).length;

    const skipped = this.records.filter(

      r => r.status === ‘skipped’

    ).length;

    const flaky = this.records.filter(

      r => r.flaky

    ).length;

    const summary = {

      executionStatus: result.status,

      total: this.records.length,

      passed,

      failed,

      skipped,

      flaky,

      duration: result.duration,

      tests: this.records

    };

    writeFileSync(

      ‘reports/custom-report.json’,

      JSON.stringify(summary, null, 2)

    );

    const headers = [

      ‘title’, ‘file’, ‘project’,

      ‘status’, ‘duration’, ‘retry’, ‘flaky’

    ];

    const csvRows = this.records.map(record =>

      [

        record.title,

        record.file,

        record.project,

        record.status,

        record.duration,

        record.retry,

        record.flaky

      ].map(value =>

        `”${String(value).replace(/”/g, ‘””‘)}”`

      ).join(‘,’)

    );

    writeFileSync(

      ‘reports/custom-report.csv’,

      [headers.join(‘,’), …csvRows].join(‘\n’)

    );

    console.log(‘Custom reports generated’);

    console.log(

      `Passed: ${passed}, Failed: ${failed}, ` +

      `Skipped: ${skipped}, Flaky: ${flaky}`

    );

  }

}

What Does This Reporter Do?

  1. Collects individual test results.
  2. Captures project and file information.
  3. Records execution duration and retry count.
  4. Identifies tests that pass after retries.
  5. Calculates execution statistics.
  6. Generates JSON and CSV reports.

The CSV example focuses on the main test fields, while the JSON report also contains error messages.

Important: A test that fails permanently after retries is counted as failed. A test that passes after one or more retries is counted as flaky rather than as a normal first-attempt pass.

Sample JSON Output

{

  “executionStatus”: “failed”,

  “total”: 5,

  “passed”: 2,

  “failed”: 1,

  “skipped”: 1,

  “flaky”: 1,

  “duration”: 12000,

  “tests”: [

    {

      “title”: “Verify login”,

      “status”: “passed”,

      “duration”: 1200,

      “retry”: 0,

      “flaky”: false

    }

  ]

}

The actual report contains additional fields such as file path, project name, and error details.

9. Configure the Custom Reporter in playwright.config.ts

After implementing the reporter, register it inside playwright.config.ts.

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

export default defineConfig({

  testDir: ‘./tests’,

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

  reporter: [

    [‘list’],

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

    [‘./reporters/customReporter.ts’]

  ],

  use: {

    screenshot: ‘only-on-failure’,

    trace: ‘on-first-retry’,

    video: ‘retain-on-failure’

  }

});

Multiple reporters can run together.

Here:

  • list displays test execution in the terminal.
  • html generates an interactive report.
  • customReporter.ts generates JSON and CSV files.

Execute the tests:

npx playwright test

After execution, check the following files:

reports/

├── custom-report.json

└── custom-report.csv

You can also view the built-in HTML report:

npx playwright show-report

10. Integrate Custom Reports with GitHub Actions or Jenkins

Custom reporting becomes more useful when integrated with CI/CD pipelines.

A. GitHub Actions Integration

Create .github/workflows/playwright.yml:

name: Playwright Custom Reporting

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – uses: actions/checkout@v6

      – uses: actions/setup-node@v6

        with:

          node-version: lts/*

          cache: npm

      – run: npm ci

      – run: npx playwright install –with-deps chromium

      – name: Run Tests

        run: npx playwright test

      – name: Upload Custom Reports

        if: ${{ !cancelled() }}

        uses: actions/upload-artifact@v5

        with:

          name: custom-playwright-reports

          path: |

            reports/

            playwright-report/

            test-results/

After execution, open the workflow run and download the report artifacts.

B. Jenkins Integration

Add the following post-execution configuration to your Jenkinsfile:

pipeline {

    agent any

    stages {

        stage(‘Install’) {

            steps {

                sh ‘npm ci’

            }

        }

        stage(‘Install Browsers’) {

            steps {

                sh ‘npx playwright install –with-deps chromium’

            }

        }

        stage(‘Run Tests’) {

            steps {

                sh ‘npx playwright test

            }

        }

    }

    post {

        always {

            archiveArtifacts(

                artifacts: ‘reports/**,playwright-report/**,test-results/**’,

                allowEmptyArchive: true

            )

        }

    }

}

This archives custom reports, screenshots, traces, and HTML reports for later analysis.

11. Troubleshooting and Best Practices

ProblemPossible reasonSolution
Custom report not generatedReporter path incorrectVerify the reporter configuration
JSON file emptyNo test results collectedCheck test discovery and execution
CSV formatting incorrectSpecial characters in test namesEscape CSV values
Flaky tests not identifiedRetry configuration disabledConfigure retries in Playwright
Reports missing in CIArtifact path incorrectVerify the reports directory
TypeScript errorsIncorrect reporter importsImport types from @playwright/test/reporter
Custom reporter crashesFile-writing or runtime errorsAdd error handling and validate output paths

Best Practices

  1. Keep reporting logic separate from test scripts.
  2. Use TypeScript interfaces for report records.
  3. Capture test duration and retry information.
  4. Generate reports in a dedicated folder.
  5. Use built-in HTML reporting alongside custom reports.
  6. Avoid including passwords, tokens, or sensitive test data in reports.
  7. Preserve reports as CI/CD artifacts.
  8. Test reporter behavior with passed, failed, skipped, and retried tests.
  9. Handle file-system errors appropriately.
  10. Keep report generation efficient for large regression suites.

Remember that Playwright catches and suppresses errors thrown by custom reporter methods. Add your own error handling and logging when report generation must be monitored reliably.

12. Frequently Asked Questions

Q1. What is Playwright TypeScript custom reporter?

A Playwright TypeScript custom reporter is a reporting component developed using TypeScript and the Playwright Reporter API. It collects test execution information and generates customized reports.

Q2. Is Playwright TypeScript custom reporter suitable for beginners?

Yes. Beginners can start by implementing onBegin(), onTestEnd(), and onEnd() before learning advanced reporting features.

Q3. What are the benefits of Playwright TypeScript custom reporter?

It provides flexible reporting, custom execution summaries, test duration tracking, flaky-test identification, and integration with CI/CD reporting systems.

Q4. Which methods are commonly used in a custom reporter?

The commonly used methods are onBegin(), onTestBegin(), onTestEnd(), and onEnd().

Q5. Can Playwright generate JSON and CSV reports?

Yes. You can implement a custom reporter using Node.js file-system methods to generate JSON and CSV files.

Q6. Can I use multiple reporters in Playwright?

Yes. Playwright supports multiple reporters simultaneously, such as HTML, list, JSON, JUnit, and custom reporters.

Q7. How do I identify flaky tests?

A test that passes after retrying can be identified using result.status === ‘passed’ and result.retry > 0.

Leave a Comment

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