Okay, let's set up some example performance tests for google.com that you can adapt for your own application and integrate into a CI/CD pipeline.
We'll cover two common approaches:
- Frontend Performance Audit using Lighthouse: Measures key user-centric metrics like First Contentful Paint (FCP), Largest Contentful Paint (LCP), Time to Interactive (TTI), and provides an overall performance score. This simulates how a real user experiences the page load in a browser.
- Basic Load/Response Time Test using k6: Measures server response times (like Time to First Byte - TTFB) and checks how the server handles a small number of concurrent requests. This focuses more on the backend/infrastructure responsiveness.
Goal: Detect performance regressions by running automated tests in CI and failing the build if key metrics drop below defined thresholds.
Target: https://www.google.com (as an example)
Example 1: Frontend Performance Audit with Lighthouse
This uses Google's Lighthouse tool, run via Node.js, suitable for many CI environments.
Prerequisites:
- Node.js and npm/yarn installed in your CI environment.
- A way to run headless Chrome (often available in CI environments, or via Puppeteer which Lighthouse can use).
Steps:
-
Install Dependencies:
npm init -y
npm install lighthouse chrome-launcher --save-dev
# or: yarn add lighthouse chrome-launcher --dev
-
Create the Test Script (lighthouse-test.js):
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const log = require('lighthouse-logger');
// Configuration
const TARGET_URL = 'https://www.google.com';
const PERF_SCORE_THRESHOLD = 90; // Example: Expect a Lighthouse performance score of at least 90
const FCP_THRESHOLD_MS = 1500; // Example: First Contentful Paint should be under 1.5 seconds
const LCP_THRESHOLD_MS = 2500; // Example: Largest Contentful Paint should be under 2.5 seconds
const TTI_THRESHOLD_MS = 3500; // Example: Time To Interactive should be under 3.5 seconds
// Suppress verbose logging, show errors
log.setLevel('error');
async function runLighthouseTest() {
let chrome;
try {
// Launch Chrome headlessly
chrome = await chromeLauncher.launch({
chromeFlags: ['--headless', '--no-sandbox', '--disable-gpu'] // Common CI flags
});
const options = {
logLevel: 'error', // Suppress Lighthouse's own logs in stdout
output: 'json', // We want structured data back
onlyCategories: ['performance'], // Only run the performance audits
port: chrome.port
};
console.log(`Running Lighthouse test for ${TARGET_URL}...`);
const runnerResult = await lighthouse(TARGET_URL, options);
const reportJson = runnerResult.lhr; // Lighthouse Result object
// Extract relevant metrics
const performanceScore = Math.round(reportJson.categories.performance.score * 100);
const fcp = Math.round(reportJson.audits['first-contentful-paint'].numericValue);
const lcp = Math.round(reportJson.audits['largest-contentful-paint'].numericValue);
const tti = Math.round(reportJson.audits['interactive'].numericValue);
const speedIndex = Math.round(reportJson.audits['speed-index'].numericValue);
const totalBlockingTime = Math.round(reportJson.audits['total-blocking-time'].numericValue);
console.log(`\nLighthouse Results for ${TARGET_URL}:`);
console.log(` Performance Score: ${performanceScore}`);
console.log(` First Contentful Paint (FCP): ${fcp}ms`);
console.log(` Largest Contentful Paint (LCP): ${lcp}ms`);
console.log(` Time to Interactive (TTI): ${tti}ms`);
console.log(` Speed Index: ${speedIndex}ms`);
console.log(` Total Blocking Time: ${totalBlockingTime}ms`);
// Check against thresholds
let failed = false;
console.log('\nChecking thresholds:');
if (performanceScore < PERF_SCORE_THRESHOLD) {
console.error(` FAIL: Performance score (${performanceScore}) is below threshold (${PERF_SCORE_THRESHOLD})`);
failed = true;
} else {
console.log(` PASS: Performance score (${performanceScore}) >= ${PERF_SCORE_THRESHOLD}`);
}
if (fcp > FCP_THRESHOLD_MS) {
console.error(` FAIL: FCP (${fcp}ms) is above threshold (${FCP_THRESHOLD_MS}ms)`);
failed = true;
} else {
console.log(` PASS: FCP (${fcp}ms) <= ${FCP_THRESHOLD_MS}ms`);
}
if (lcp > LCP_THRESHOLD_MS) {
console.error(` FAIL: LCP (${lcp}ms) is above threshold (${LCP_THRESHOLD_MS}ms)`);
failed = true;
} else {
console.log(` PASS: LCP (${lcp}ms) <= ${LCP_THRESHOLD_MS}ms`);
}
if (tti > TTI_THRESHOLD_MS) {
console.error(` FAIL: TTI (${tti}ms) is above threshold (${TTI_THRESHOLD_MS}ms)`);
failed = true;
} else {
console.log(` PASS: TTI (${tti}ms) <= ${TTI_THRESHOLD_MS}ms`);
}
if (failed) {
console.error('\nPerformance regression detected!');
return false; // Indicate failure
} else {
console.log('\nPerformance thresholds met.');
return true; // Indicate success
}
} catch (error) {
console.error('Error running Lighthouse test:', error);
return false; // Indicate failure
} finally {
if (chrome) {
await chrome.kill(); // Ensure Chrome process is closed
}
}
}
// Run the test and exit with appropriate code for CI
runLighthouseTest().then(success => {
process.exit(success ? 0 : 1); // Exit 0 on success, 1 on failure
});
-
Add a script to package.json:
{
"name": "perf-test-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test:perf:lighthouse": "node lighthouse-test.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"chrome-launcher": "^0.15.0", // Use appropriate version
"lighthouse": "^9.6.0" // Use appropriate version
}
}
-
Run Locally:
npm run test:perf:lighthouse
# or
yarn test:perf:lighthouse
-
CI Integration (Example using GitLab CI):
# .gitlab-ci.yml
stages:
- test
performance_test:
stage: test
image: node:16 # Choose a Node image with Chrome/Puppeteer support or install it
before_script:
- apt-get update && apt-get install -y wget --no-install-recommends # Example for Debian/Ubuntu based image
- wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
- sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
- apt-get update && apt-get install -y google-chrome-stable --no-install-recommends # Install Chrome if not present
- npm install --progress=false # Install node dependencies
script:
- npm run test:perf:lighthouse # Run the test script
artifacts:
when: always # Or on_failure
paths:
- lighthouse-report.html # If you modify the script to save HTML report
- lighthouse-report.json # If you modify the script to save JSON report
Note: Adjust the image and before_script based on your CI environment and how Chrome is made available.
Example 2: Basic Load/Response Time with k6
This uses k6, a modern load testing tool. It's great for testing API endpoints or simple page loads under concurrent load.
Prerequisites:
- k6 installed in your CI environment (available as a binary or Docker image).
Steps:
-
Install k6: Follow instructions at https://k6.io/docs/getting-started/installation/
-
Create the k6 Test Script (k6-test.js):
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Trend, Rate, Counter } from 'k6/metrics';
// Configuration
const TARGET_URL = 'https://www.google.com';
// Custom Metrics (optional but good practice)
const TtfbTrend = new Trend('ttf_trend', true); // Track Time to First Byte trend
const ErrorRate = new Rate('error_rate'); // Track the rate of failed requests
// Test Options
export const options = {
vus: 5, // Number of virtual users simulating concurrent access
duration: '30s', // Duration of the test
thresholds: {
// Define success criteria (test will fail if these aren't met)
'http_req_duration{status:200}': ['p(95)<500'], // 95% of requests with status 200 should be below 500ms total duration
'ttf_trend{status:200}': ['p(95)<300'], // 95% of TTFBs for status 200 requests should be below 300ms
'checks': ['rate>0.99'], // More than 99% of checks should pass
'error_rate': ['rate<0.01'], // Error rate should be less than 1%
},
};
// Main test function executed by each VU
export default function () {
const res = http.get(TARGET_URL, {
tags: { name: 'HomePage' } // Tag requests for better filtering in results
});
// Check response status
const statusCheck = check(res, {
'status is 200': (r) => r.status === 200,
});
// Record metrics
ErrorRate.add(!statusCheck); // Add error if check failed
if (res.status === 200) {
TtfbTrend.add(res.timings.waiting); // Add TTFB to our custom trend (waiting time in k6)
}
sleep(1); // Wait for 1 second between requests per VU
}
-
Run Locally:
k6 run k6-test.js
k6 will output summary statistics and indicate PASS/FAIL based on the thresholds.
-
CI Integration (Example using GitLab CI with Docker):
# .gitlab-ci.yml
stages:
- test
performance_test_k6:
stage: test
image: grafana/k6:latest # Use the official k6 Docker image
script:
# The k6 Docker image runs k6 directly. We just pass the script path.
# Assuming k6-test.js is in the root of your repo.
- k6 run k6-test.js
Choosing the Right Approach & Considerations
- Lighthouse: Best for measuring the user-perceived frontend performance of specific pages. Good for catching regressions in JS bundle size, CSS efficiency, image loading, critical rendering path. Results can be sensitive to CI runner performance and network conditions.
- k6: Best for testing server response time, API endpoint performance, and behavior under load. Less sensitive to frontend changes, more focused on backend/infrastructure. Can simulate many users.
- Combination: Often, you'll want both. Lighthouse for key landing pages/user flows and k6 for critical API endpoints and overall site responsiveness under load.
- Thresholds are Key: Setting the right thresholds is crucial and requires observation.
- Run the tests multiple times on your
main branch to establish a baseline.
- Set thresholds slightly looser than the absolute best results to avoid flaky tests due to minor network fluctuations or CI runner variance.
- Adjust thresholds over time as your application evolves or infrastructure changes.
- Target Environment: Ideally, run performance tests against a staging environment that closely mirrors production in terms of hardware, configuration, and data. Running against production directly can be risky and results might be skewed by live traffic. (Using
google.com here is just for demonstration).
- Consistency: CI environments can vary. Try to use consistent runner types. Consider running tests multiple times and averaging, or using P90/P95 metrics which are less sensitive to outliers than averages.
- Reporting: Basic CI logs show pass/fail. For more detail, configure Lighthouse to save HTML/JSON reports as artifacts, or use k6 Cloud / InfluxDB+Grafana for visualizing k6 results over time.
- Complexity: Start simple (like the examples above) and add more complex scenarios (e.g., testing logged-in user flows, testing specific API POST requests with k6) as needed.
Adapt these examples by changing the TARGET_URL and tuning the thresholds based on your application's specific performance characteristics and goals.