Parrot Middleware for Express

5.3.0 · active · verified Wed Apr 22

parrot-middleware is an Express.js middleware designed for mocking HTTP requests in development and testing environments. It allows developers to define a collection of 'scenarios', each comprising a list of request-response pairs. Based on the active scenario, the middleware intercepts matching incoming requests and serves the predefined mock responses. It provides dedicated control routes (`/parrot/scenario` for setting/getting the active scenario, and `/parrot/scenarios` for inspecting all available scenarios) to manage its behavior dynamically. Currently at stable version 5.3.0, the package sees active maintenance with frequent patch and minor releases, ensuring compatibility and addressing issues. Its key differentiator is the scenario-driven approach, making it easy to simulate complex backend states or error conditions without modifying frontend code or spinning up a full backend.

Common errors

Warnings

Install

Imports

Quickstart

This example sets up an Express server with `parrot-middleware`, defining two basic scenarios. It demonstrates how to initialize the middleware with scenario definitions and provides instructions on how to activate a scenario via a POST request and then fetch the mocked data.

import express from 'express';
import parrot from 'parrot-middleware';

// scenarios.js
const scenarios = {
  'has one ship': [
    {
      request: '/ship_log',
      response: {
        body: [{ name: 'The Jolly Roger', captain: 'Captain Hook' }],
      },
    },
  ],
  'has more ships': [
    {
      request: '/ship_log',
      response: {
        body: [
          { name: 'The Jolly Roger', captain: 'Captain Hook' },
          { name: 'The Black Pearl', captain: 'Jack Sparrow' },
        ],
      },
    },
  ],
};

const app = express();

app.use(express.json()); // Required for parsing JSON bodies for scenario POST requests
app.use(parrot(scenarios));

app.get('/', (req, res) => res.send('Hello from main app!'));

app.listen(3001, () => {
  console.log('Server running on http://localhost:3001');
  console.log('Try: POST http://localhost:3001/parrot/scenario with { "scenario": "has one ship" }');
  console.log('Then: GET http://localhost:3001/ship_log');
});

view raw JSON →