Implementation:Puppeteer Puppeteer TestServer
| Property | Value |
|---|---|
| sources | packages/testserver/src/index.ts |
| domains | Testing Infrastructure, HTTP Server, WebSocket Server |
| last_updated | 2026-02-12 00:00 GMT |
Overview
Description
The TestServer class implements a configurable HTTP/HTTPS test server used extensively throughout Puppeteer's test suite. It provides a static file server with rich configuration capabilities for simulating various web server behaviors during end-to-end testing.
Key features include:
- Static file serving -- Serves files from a specified directory with proper MIME type detection via the
mimelibrary and UTF-8 encoding for text content types - HTTPS support -- Supports SSL/TLS via
createHttpsServerwith configurable certificate and key options - WebSocket support -- Includes a
WebSocketServerthat sends an "opened" message on connection - Custom route handlers -- Routes can be registered to intercept specific paths with custom request/response logic
- HTTP authentication -- Basic authentication can be configured per path
- Content Security Policy -- CSP headers can be set per path
- GZIP compression -- Selective gzip encoding support for specific paths
- HTTP caching -- Configurable cache headers with
If-Modified-Since/304 Not Modifiedsupport - Redirect support -- Routes can be configured to issue
302redirects - Request interception -- Asynchronous waiting for specific request paths with
waitForRequest - Connection management -- Tracks active connections for clean shutdown, handles ECONNRESET gracefully
The server binds to an ephemeral port (port 0) and exposes convenience properties: PORT, PREFIX, CROSS_PROCESS_PREFIX, and EMPTY_PAGE.
Usage
The TestServer is instantiated in Puppeteer's test setup for both HTTP and HTTPS configurations. Tests use it to serve HTML pages, simulate network conditions, test authentication, verify caching behavior, and exercise WebSocket functionality.
Code Reference
Source Location
packages/testserver/src/index.ts
Signature
export class TestServer {
PORT: number;
PREFIX: string;
CROSS_PROCESS_PREFIX: string;
EMPTY_PAGE: string;
static async create(dirPath: string): Promise<TestServer>;
static async createHTTPS(dirPath: string): Promise<TestServer>;
constructor(dirPath: string, sslOptions?: HttpsServerOptions);
get port(): number;
enableHTTPCache(pathPrefix: string): void;
setAuth(path: string, username: string, password: string): void;
enableGzip(path: string): void;
setCSP(path: string, csp: string): void;
async stop(): Promise<void>;
setRoute(path: string, handler: (req: IncomingMessage, res: ServerResponse) => void): void;
setRedirect(from: string, to: string): void;
waitForRequest(path: string): Promise<IncomingMessage & {postBody?: Promise<string>}>;
reset(): void;
serveFile(request: IncomingMessage, response: ServerResponse, pathName: string): void;
}
Import
import {TestServer} from '@puppeteer/testserver';
I/O Contract
Factory Methods
| Method | Parameters | Return Type | Description |
|---|---|---|---|
| create | dirPath: string |
Promise<TestServer> |
Creates an HTTP server serving files from dirPath on a random port |
| createHTTPS | dirPath: string |
Promise<TestServer> |
Creates an HTTPS server with bundled test certificates |
Instance Properties
| Property | Type | Description |
|---|---|---|
| PORT | number |
Bound port number |
| PREFIX | string |
Full URL prefix (e.g., http://localhost:8907)
|
| CROSS_PROCESS_PREFIX | string |
URL using 127.0.0.1 for cross-origin testing |
| EMPTY_PAGE | string |
URL to /empty.html
|
Configuration Methods
| Method | Parameters | Description |
|---|---|---|
| setRoute | path, handler |
Register a custom handler for a specific URL path |
| setRedirect | from, to |
Configure a 302 redirect from one path to another |
| setAuth | path, username, password |
Require Basic authentication for a path |
| setCSP | path, csp |
Set Content-Security-Policy header for a path |
| enableGzip | path |
Enable gzip compression for a specific path |
| enableHTTPCache | pathPrefix |
Enable HTTP caching (Last-Modified/If-Modified-Since) for paths |
| reset | none | Clear all routes, auth, CSP, gzip settings, and pending request subscribers |
| stop | none | Destroy all connections and close the server |
Usage Examples
import {TestServer} from '@puppeteer/testserver';
// Create an HTTP test server
const server = await TestServer.create('/path/to/test/assets');
console.log(server.PREFIX); // 'http://localhost:12345'
console.log(server.EMPTY_PAGE); // 'http://localhost:12345/empty.html'
// Create an HTTPS test server
const httpsServer = await TestServer.createHTTPS('/path/to/test/assets');
// Set a custom route
server.setRoute('/json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({status: 'ok'}));
});
// Set up authentication
server.setAuth('/protected', 'admin', 'password');
// Set a redirect
server.setRedirect('/old-page', '/new-page');
// Wait for a specific request
const requestPromise = server.waitForRequest('/api/data');
// ... trigger the request from browser ...
const request = await requestPromise;
const body = await request.postBody;
// Enable gzip for a path
server.enableGzip('/compressed.html');
// Set CSP header
server.setCSP('/secure.html', "default-src 'self'");
// Clean up
server.reset();
await server.stop();