unexpected-express

raw JSON →
13.1.2 verified Sat Apr 25 auth: no javascript

Plugin for the Unexpected assertion library that allows testing Express.js middleware by simulating HTTP requests and inspecting responses, status codes, headers, and body. Current stable version 13.1.2. Released as needed, follows semver. Differentiators: uses unexpected-messy for powerful HTTP assertion capabilities, integrates deeply with Unexpected's fluent API, and supports Express 4.x.

error TypeError: unexpectedExpress is not a function
cause Using named import instead of default import
fix
Use import unexpectedExpress from 'unexpected-express'
error Error: Cannot find module 'unexpected-express'
cause Package not installed or installed as dev dependency and missing in production
fix
Run npm install --save-dev unexpected-express
error TypeError: expect(...).to is not a function
cause Forgetting to use the cloned expect instance with the plugin installed
fix
Use const expect = unexpected.clone().use(unexpectedExpress);
breaking ESM-only since version 13: CommonJS require() will not work
fix Use import syntax or migrate to an older version (e.g., 12.x) if CJS required
gotcha unexpected Express is a default export, not a named export
fix Use `import unexpectedExpress from 'unexpected-express'`
deprecated The plugin uses unexpected-messy internally; some low-level HTTP assertion methods may change
fix Refer to unexpected-express documentation; avoid relying on unexpected-messy directly
gotcha The 'to yield exchange' assertion expects a full request string and response object; missing headers or body details may cause false failures
fix Always specify at least statusCode and body if needed
npm install unexpected-express
yarn add unexpected-express
pnpm add unexpected-express

Demonstrates testing an Express route that returns JSON based on request params

import unexpected from 'unexpected';
import unexpectedExpress from 'unexpected-express';
import express from 'express';

const expect = unexpected.clone().use(unexpectedExpress);

const app = express();
app.get('/user/:id', (req, res) => {
  res.json({ id: req.params.id });
});

await expect(app, 'to yield exchange', {
  request: 'GET /user/42',
  response: { statusCode: 200, body: { id: '42' } }
});