All Projects → pmu-tech → stub-server

pmu-tech / stub-server

Licence: MIT License
Stub server for REST APIs

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to stub-server

Stubmatic
Mock HTTP calls without coding. Designed specially for testing and testers.
Stars: ✭ 118 (+742.86%)
Mutual labels:  mock, stub, fake, stub-server
Hippolyte
HTTP Stubbing in Swift
Stars: ✭ 109 (+678.57%)
Mutual labels:  mock, test, stub
node-mock-examples
Examples of tests that mock Node system APIs: fs, http, child_process, timers
Stars: ✭ 38 (+171.43%)
Mutual labels:  mock, test, stub
Fake server
FakeServer integrates with ExUnit to make external APIs testing simpler
Stars: ✭ 64 (+357.14%)
Mutual labels:  test, stub, fake
Impersonator
Ruby library to record and replay object interactions
Stars: ✭ 100 (+614.29%)
Mutual labels:  mock, stub, fake
aem-stubs
Tool for providing sample data for AEM applications in a simple and flexible way. Stubbing server on AEM, no separate needed.
Stars: ✭ 40 (+185.71%)
Mutual labels:  mock, stub, stub-server
ts-mock-imports
Intuitive mocking library for Typescript class imports
Stars: ✭ 103 (+635.71%)
Mutual labels:  mock, stub, fake
sinon-mongoose
Extend Sinon stubs for Mongoose methods to test chained methods easily
Stars: ✭ 87 (+521.43%)
Mutual labels:  mock, stub
FireMock
Mock and stub HTTP requests. Test your apps with fake data and files responses.
Stars: ✭ 25 (+78.57%)
Mutual labels:  mock, stub
laika
Log, test, intercept and modify Apollo Client's operations
Stars: ✭ 99 (+607.14%)
Mutual labels:  mock, test
Mockaco
🐵 HTTP mock server, useful to stub services and simulate dynamic API responses, leveraging ASP.NET Core features, built-in fake data generation and pure C# scripting
Stars: ✭ 213 (+1421.43%)
Mutual labels:  mock, fake
fakey-json
This is a utility for mocking json data that pretends the api response data with JSON format.
Stars: ✭ 27 (+92.86%)
Mutual labels:  mock, fake
Faker.Portable
C# faked data generation for testing and prototyping purpose.
Stars: ✭ 12 (-14.29%)
Mutual labels:  stub, fake
jest-ts-auto-mock
Jest test utility with automatic mock creation for interfaces and classes
Stars: ✭ 150 (+971.43%)
Mutual labels:  mock, fake
htest
htest is a http-test package
Stars: ✭ 24 (+71.43%)
Mutual labels:  mock, test
jest-launchdarkly-mock
Easily unit test LaunchDarkly feature flagged components with jest
Stars: ✭ 14 (+0%)
Mutual labels:  mock, test
dextool
Suite of C/C++ tooling built on LLVM/Clang
Stars: ✭ 81 (+478.57%)
Mutual labels:  mock, test
moq.ts
Moq for Typescript
Stars: ✭ 107 (+664.29%)
Mutual labels:  mock, fake
mock
Utilities to help mock behavior, spy on function calls, stub methods, and fake time for tests.
Stars: ✭ 31 (+121.43%)
Mutual labels:  mock, stub
better-mock
Forked from Mockjs, Generate random data & Intercept ajax request. Support miniprogram.
Stars: ✭ 140 (+900%)
Mutual labels:  mock, fake

@pmu-tech/stub-server

npm version Node.js CI Bundle size Prettier Airbnb Code Style

Stub/mock server for REST APIs

For each route, decide what will happen: a JSON stub, a piece of JS or redirect to a real server

  • Use it with Express, webpack-dev-server, Next.js or the command line
  • Support stubs written in JSON, JS, TypeScript, HTML, jpg...
  • Can redirect requests to another host thx to node-http-proxy
  • No need to restart stub-server if you modify a stub
  • The HTTP status code returned is determined from the stub filename: *_200_*.json, *_500_*.html...
  • Configurable delays to simulate slow APIs
  • Configurable HTTP headers (useful to change origin and bypass CORS for some APIs)

Usage

npm install --save-dev @pmu-tech/stub-server

Proposed file organization

stubs/routes/my_api1_GET_200_OK.json
             my_api2_GET_200_OK.jpg
             my_api3_POST_400_BadRequest-invalidField.ts
             my_api4_POST_400_BadRequest-invalidField.js
             my_api5_DELETE_500_InternalServerError.html
             my_api7_GET_200_OK.json
             my_api7_POST_200_OK.json
             my_api8_GET.ts
             my_api9_GET.js
             my_api10_GET_200_OK-param1.json
             my_api10_GET_200_OK-param2.json
stubs/config.ts
webpack.config.ts

stubs/config.ts

import path from 'path';
import { StubServerConfig } from '@pmu-tech/stub-server';

const prod = 'https://pmu.fr';

const stubsPath = path.resolve(__dirname, 'routes');

const config: StubServerConfig = {
  delay: { min: 500, max: 3000 },
  routes: {
    '/my/api1': { GET: `${stubsPath}/my_api1_GET_200_OK.json` },
    '/my/api2': { GET: `${stubsPath}/my_api2_GET_200_OK.jpg` },
    '/my/api3': { POST: `${stubsPath}/my_api3_POST_400_BadRequest-invalidField.ts` },
    '/my/api4': { POST: `${stubsPath}/my_api4_POST_400_BadRequest-invalidField.js` },
    '/my/api5': { DELETE: `${stubsPath}/my_api5_DELETE_500_InternalServerError.html` },
    '/my/api6/:id': { PUT: prod },
    '/my/api7': {
      delay: { min: 1000, max: 1000 },
      GET: `${stubsPath}/my_api7_GET_200_OK.json`,
      POST: {
        delay: { min: 0, max: 0 },
        headers: { origin: 'https://pmu.fr' },
        response: `${stubsPath}/my_api7_POST_200_OK.json`
      }
    },
    '/my/api8': { GET: `${stubsPath}/my_api8_GET.ts`},
    '/my/api9': { GET: `${stubsPath}/my_api9_GET.js`},
    '/my/api10/:id': { GET: req => `${stubsPath}/my_api10_GET_200_OK-${req.params.id}.json` }
  }
};

const rootApiPath = 'https://pmu.fr/client/:clientApi';
config.routes[`${rootApiPath}/my/api7`] = { GET: `${stubsPath}/my_api7_GET_200_OK.json` };

export default config; // Or "exports.default = config"

Note: stubs/config.ts written in TypeScript instead of JavaScript requires ts-node

webpack.config.ts

Configuration with webpack-dev-server

import { stubServer } from '@pmu-tech/stub-server';

// ...

  devServer: {
    // ...

    // webpack 5
    onBeforeSetupMiddleware: ({ app }) => {
      const configPath = path.resolve(__dirname, 'stubs', 'config');
      stubServer(configPath, app);
    }

    // webpack 4
    before: app => {
      const configPath = path.resolve(__dirname, 'stubs', 'config');
      stubServer(configPath, app);
    }

    // ...
  },

// ...

stubs/routes/my_api1_GET_200_OK.json

{
  "foo": "bar"
}

stubs/routes/my_api3_POST_400_BadRequest-invalidField.ts

export default {
  error: 'Invalid field'
};

stubs/routes/my_api4_POST_400_BadRequest-invalidField.js

module.exports = {
  error: 'Invalid field'
};

stubs/routes/my_api8_GET.ts

import express from 'express';

export default function stub(req: express.Request, res: express.Response) {
  res.send('Hello, World!');
}

stubs/routes/my_api9_GET.js

module.exports = (req, res) => {
  res.send('Hello, World!');
};

Command line

Usage: stub-server [options] <config>

Arguments:
  config         path to the config file

Options:
  --port <port>  stub server port (default: "12345")
  --no-delay     ignore any delay specified in the config
  -h, --help     display help for command

Next.js

// stubServer.js

const { stubServer } = require('@pmu-tech/stub-server');
const cors = require('cors');
const express = require('express');
const next = require('next');
const Log = require('next/dist/build/output/log');
const path = require('path');

const app = next({ dev: process.env.NODE_ENV !== 'production' });
const handle = app.getRequestHandler();

const configPath = path.resolve(__dirname, 'stubs', 'config');
const port = 3000;

app.prepare().then(() => {
  const server = express();
  server.use(express.json());
  server.use(cors());

  stubServer(configPath, server);

  server.all('*', (req, res) => handle(req, res));

  server.listen(port, () => {
    // https://github.com/zeit/next.js/blob/v9.3.1/packages/next/build/output/store.ts#L85-L88
    Log.ready(`ready on port ${port}`);
  });
});
// package.json

{
  "scripts": {
    "dev": "node stubServer.js", // Instead of "next dev"
    "build": "next build",
    "start": "next start"
  }
}

Errors

If an error occurs (missing stub or route) while stub-server is processing a request, the error is returned in the response with status 500 (Internal Server Error) and is also displayed in the console.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].