Debug School

rakesh kumar
rakesh kumar

Posted on

How to Test Laravel Applications with Pest, Playwright, k6, and OWASP ZAP

A Laravel application needs several kinds of evidence before a release. Business rules must produce correct results, browser journeys must work, APIs must meet performance targets, and access controls must protect customer data. Each testing tool answers a different question.

This guide proposes a practical stack for a Laravel backend with a React frontend. It also works for Blade applications. The browser examples use Python Playwright so teams with an existing pytest suite can reuse their tests.

Choose a Tool for Each Testing Layer

Testing need Suggested tool What to verify
Unit tests Pest or PHPUnit Calculations, services, helpers, business rules
Feature and API tests Pest/PHPUnit with Laravel HTTP testing Routes, validation, policies, authentication, database changes
Browser journeys Playwright Navigation, login, forms, role-specific screens
Performance and load Grafana k6 Latency, error rate, throughput, behavior under traffic
Web security scanning OWASP ZAP Findings visible in reachable responses and application behavior
Static analysis PHPStan with Larastan Type errors and Laravel-aware code analysis
Formatting Laravel Pint Consistent PHP code style
Dependency advisories Composer audit and frontend dependency scanning Known vulnerabilities in installed dependencies
Automation GitHub Actions Repeatable checks and saved reports

Laravel supports Pest and PHPUnit. Use the framework's testing environment and an isolated test database for database-backed tests. Select package versions compatible with the application's PHP and Laravel versions. Laravel testing documentation

Start with Laravel Unit and Feature Tests

Keep calculations and business rules easy to exercise without a browser. For example, test that a quote total correctly includes its configured fees and that a hospital can accept only the bids permitted by its policy.

A minimal Pest feature test can check an existing public route. Save this example as tests/Feature/HomepageTest.php in a Laravel project whose root route returns a successful response.

<?php

test('homepage responds successfully', function () {
    $response = $this->get('/');

    $response->assertOk();
});
Enter fullscreen mode Exit fullscreen mode

Run the suite from the Laravel project root after setting up its testing environment.

php artisan test
Enter fullscreen mode Exit fullscreen mode

Extend feature coverage to required fields, invalid values, authorized actions, unauthorized access, and database effects. Use factories and Laravel's database testing support when a test creates data. Confirm the database configuration before running migrations or reset traits. These tests should exercise the actual policy and service behavior the application uses. Laravel testing documentation

Use Playwright for Browser Journeys

Playwright exercises the rendered interface and its browser interactions. Your existing Python smoke suite is a suitable starting point. Add a few important journeys, then expand regression coverage as bugs are discovered.

The following pytest example assumes BASE_URL identifies your test deployment and the page has a visible level-one heading.

import os

from playwright.sync_api import Page, expect


def test_homepage_has_main_heading(page: Page):
    base_url = os.environ['BASE_URL'].rstrip('/')
    response = page.goto(base_url)

    assert response is not None
    assert response.status == 200
    expect(page.get_by_role('heading', level=1)).to_be_visible()
Enter fullscreen mode Exit fullscreen mode

Install and run the Python browser tooling in your project's virtual environment.

python -m pip install pytest pytest-playwright
python -m playwright install chromium
python -m pytest tests/browser --browser chromium --junitxml=results/browser.xml --screenshot=only-on-failure --tracing=retain-on-failure --output=results/browser-artifacts
Enter fullscreen mode Exit fullscreen mode

Adapt the test path and heading locator to your application. Failure screenshots and retained traces help explain what the browser encountered. Keep the existing public smoke suite small, while using staging accounts and sandbox integrations for registration, booking, payment, and administration journeys. The pytest plugin provides the screenshot and trace options shown above. Playwright pytest reference

What Is k6?

Grafana k6 runs scripted workloads against an application and measures performance. A virtual user repeatedly executes the scenario you define. A scenario can represent browsing a listing, searching, authenticating, or submitting a booking.

An HTTP virtual user makes the requests written in the script. A full page visit can involve many additional assets and API calls, so model those requests deliberately when estimating real visitor behavior.

Workload Question it answers
Small performance smoke run Does the scenario run successfully with minimal traffic?
Expected-load test Can the application meet its targets at expected traffic?
Stress test Where does performance become unacceptable?
Spike test How does the system respond to a sudden increase?
Soak test Does performance deteriorate during sustained traffic?

A Small k6 Example with CI Thresholds

Save this as tests/performance/products.js. Configure BASE_URL to point to a staging deployment and replace /api/products with an existing public endpoint. The starting workload is deliberately small and should be adjusted using your actual traffic and capacity.

import http from 'k6/http';
import { check, sleep } from 'k6';

const baseUrl = __ENV.BASE_URL;
if (!baseUrl) {
  throw new Error('Set BASE_URL to your staging deployment.');
}

export const options = {
  vus: 5,
  duration: '30s',
  thresholds: {
    http_req_failed: ['rate<0.01'],
    http_req_duration: ['p(95)<500'],
    checks: ['rate==1'],
  },
};

export default function () {
  const response = http.get(`${baseUrl.replace(/\/$/, '')}/api/products`, {
    tags: { name: 'GET /api/products' },
  });

  check(response, {
    'status is 200': (result) => result.status === 200,
  });

  sleep(1);
}
Enter fullscreen mode Exit fullscreen mode

Once k6 is installed, run this in Windows PowerShell.

$env:BASE_URL = 'https://staging.your-domain.example'
k6 run tests/performance/products.js
Enter fullscreen mode Exit fullscreen mode

The thresholds require fewer than 1% failed HTTP requests, a 95th-percentile response time below 500 ms, and every custom check to pass. These values illustrate a policy that your team must set for each endpoint. A failed check() by itself records a failed check. Thresholds give k6 a failing exit status suitable for CI. k6 thresholds and k6 checks

Interpret the Results with Server Metrics

Record response-time percentiles, request rate, error rate, and the workload alongside server CPU, memory, database query latency, connection usage, and queue depth. A rise in p95 latency tells you that requests slowed down. Query logs, application tracing, and resource metrics help locate the bottleneck.

Five virtual users do not imply five requests per second. Request duration, the one-second pause, and scenario logic determine throughput. Increase the workload progressively and keep the environment, dataset, and scenario comparable across runs. k6 metrics

For write scenarios, use isolated test records, sandbox payments, and controlled email or SMS delivery. Include authentication and session behavior appropriate to your application. Point load tests at a staging environment sized and configured to support the intended experiment.

Build Security Coverage with ZAP and Explicit Access Tests

ZAP's baseline scan crawls the target and reports findings from passive scanning. Its discovery requests create traffic and may execute application behavior. Start with a scoped staging deployment and review reachable routes. Authenticated pages need configured authentication or another method of exposing their traffic to the scanner. ZAP baseline scan and ZAP getting started

With Docker installed, this illustrative command runs a short baseline scan against a placeholder staging URL.

docker run --rm ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://staging.your-domain.example -m 1
Enter fullscreen mode Exit fullscreen mode

Use ZAP report options and a writable mounted output directory when retaining reports. Review findings by evidence, severity, and application context. Establish a version-controlled rule configuration to determine which findings block CI, and give accepted exceptions an owner and review date. ZAP baseline options and exit codes

Full and API scans can perform active attacks against discovered endpoints. Run them in a deliberately scoped environment prepared for those interactions. The baseline, full, and API scan modes have different behavior. ZAP Docker scan modes

Add explicit Laravel feature tests for business-specific security rules. Examples include a patient accessing another patient's quote, a hospital modifying another hospital's bid, and a regular user opening an administrator operation. Verify the expected denial and the absence of unauthorized database changes. Code review should also examine validation, query construction, file uploads, and sensitive-data handling.

Add Static Analysis and Dependency Checks

Use Larastan as PHPStan's Laravel extension, then configure it for the repository's application paths. Pint's --test option checks formatting. Run Composer audit alongside a suitable scan for the frontend package manager. These commands assume the relevant tools and configuration are installed.

php artisan test
vendor/bin/phpstan analyse
vendor/bin/pint --test
composer audit
Enter fullscreen mode Exit fullscreen mode

Static analysis, style checks, and dependency advisories each supply different evidence for release review. Choose a manageable initial PHPStan level and improve coverage as existing findings are resolved. Larastan project and Laravel Pint

A Practical GitHub Actions Pipeline

Use a fast pull-request pipeline and scheduled deeper checks. The following is a proposed cadence, to adapt to suite duration and deployment resources.

Trigger Work to run Results to retain
Pull request Laravel tests, static analysis, formatting, dependency checks Test reports and diagnostics
Pull-request preview or trusted staging deployment Critical Playwright journeys, small k6 scenario, ZAP baseline Browser evidence, performance output, security findings
Nightly Wider browser regression and representative load Trends and failed-test evidence
Weekly or before a major release Longer load/soak scenarios and scoped active scans Capacity findings and reviewed security reports
Production deployment Small public smoke suite URL status, test name, failure reason, timestamp

Prepare dependencies and an isolated database, run migrations, start or deploy the application, wait for readiness, and then execute network-based checks. A staging test needs the deployment containing the commit under review. A shared staging instance should have coordinated runs so competing deployments or load tests do not invalidate results.

Upload reports even when a test fails, while preserving the test command's failure exit status. Keep secrets in the intended GitHub environment, restrict artifact access and retention, and avoid exposing credentials in traces. GitHub withholds ordinary Actions secrets from fork pull requests, so use an appropriate trusted deployment path for tests requiring those secrets. GitHub workflow artifacts and GitHub secret types

Show Results in a FastAPI, React, and PostgreSQL Dashboard

For a team reviewing CI logs manually, a dashboard can preserve and present outcomes from all these tools. Each runner should emit structured results that an importer maps to a shared run record.

Store the project, environment, commit, tool, test identifier, URL where available, status, duration, failure reason, and artifact references. Include tool-specific evidence such as k6 thresholds and ZAP rule identifiers. A performance scenario may span multiple URLs, so retain the scenario identity as well.

A Run Again action should create a new execution, save its results, and update the displayed latest completed result. Preserve the previous failure in history. Opening or refreshing the table should read saved PostgreSQL results. Capture launch errors, collection errors, and interrupted executions so the interface accurately explains what happened.

How to Choose Between Playwright and Selenium

For a team already using Python Playwright, continuing that suite avoids a migration and reuses its fixtures, screenshots, and traces. Playwright also offers JavaScript/TypeScript tooling, so the choice does not depend on requiring a JavaScript-only test ecosystem.

Selenium remains relevant when an existing WebDriver or Grid investment, required browser combination, or organizational tooling calls for it. Native mobile application testing calls for evaluating Appium and the required device automation separately. Verify actual browser and device requirements before choosing a cloud device provider. Selenium WebDriver and Playwright Python pytest support

Roll Out the Stack in Manageable Steps

  1. Add unit and feature tests for important business rules and authorization.
  2. Keep a small Playwright smoke suite, then cover the critical user journeys.
  3. Establish a measured k6 baseline and endpoint-specific performance targets.
  4. Review ZAP baseline findings and add scoped authenticated coverage.
  5. Automate checks and retain the evidence needed to diagnose failures.
  6. Track results over time and add regression tests for confirmed bugs.

The example endpoints and thresholds in this article are illustrative. The snippets have not been executed against a project. Adapt them to the installed versions, routes, test data, and deployment environment before running them.

Top comments (0)