Server Orchestration for E2E Tests

2.1.0 · active · verified Tue Apr 21

The `with-server` package is a command-line utility and programmatic API designed to orchestrate local server startup, command execution (typically end-to-end tests), and server shutdown. It automatically handles port allocation via the `$PORT` environment variable, waits for the server to become ready, and exposes `$SERVER_URL` to the executed command. It offers options to specify the server's start script and control output redirection. The current stable version is 2.1.0, with releases appearing infrequently, driven by feature additions or critical maintenance, such as the major Node.js version bump in v2.0.0. It's a focused tool for e2e testing workflows, abstracting away the complexities of server lifecycle management during test runs, differentiating itself by its simplicity and direct integration with npm scripts.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates programmatic usage of `with-server` to run a test command (e.g., Cypress) against a local server, specifying the server start script and output redirection, and handling the exit code.

const withServer = require("with-server");

async function runTests() {
  console.log('Starting server and running tests...');
  try {
    const exitCode = await withServer("cypress run", {
      run: "start", // Assuming 'npm start' is the command to launch your server
      redirect: "stderr", // Redirect server logs to stderr to keep test output clean
      // Additional options like 'port' can be specified if you need a fixed port
    });
    console.log(`Test command exited with code: ${exitCode}`);
    process.exit(exitCode);
  } catch (error) {
    console.error('An error occurred:', error.message);
    process.exit(1);
  }
}

// Example package.json script for demonstration:
// "scripts": {
//   "start": "node server.js",
//   "test:e2e": "node run-tests.js"
// }
// Where server.js might look like:
// const http = require('http');
// const port = process.env.PORT || 3000;
// http.createServer((req, res) => res.end('Hello from server')).listen(port, () => console.log(`Server listening on port ${port}`));

runTests();

view raw JSON →