npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

spur-mockserver

v2.0.1

Published

A Node.js library with tools to allow for the creation of mock web servers for testing with mocks and real web servers.

Downloads

94

Readme

A Node.js library with tools to allow for the creation of mock web servers for testing with mocks and real web servers.

NPM Version NPM Install Size NPM Downloads

About the Spur Framework

The Spur Framework is a collection of commonly used Node.JS libraries used to create common application types with shared libraries.

Visit NPMJS.org for a full list of Spur Framework libraries >>

Topics

Quick start

Installing

Dependencies:

$ npm install --save spur-ioc spur-config spur-common spur-web

Module:

$ npm install spur-mockserver --save

Usage

Standalone usage example

This example will only show the files that show unique configurations to a mock server. For a fully detailed example, please view the example here.

src/injector.js

const path = require('path');
const spur = require('spur-ioc');
const spurCommon = require('spur-common');
const spurWeb = require('spur-web');
const spurMockserver = require('spur-mockserver');
const spurConfig = require('spur-config');
const registerConfig = require('spur-common/registerConfig');

module.exports = function () {

  const ioc = spur.create('spur-mockserver-example');

  registerConfig(ioc, path.join(__dirname, './config'));

  ioc.merge(spurCommon());
  ioc.merge(spurWeb());
  ioc.merge(spurMockserver());

  ioc.registerFolders(__dirname, [
    'mocks/'
    'runtime/'
  ]);

  return ioc;
};

src/runtime/WebServer.js

module.exports = function (MockWebServer) {
  class WebServer extends MockWebServer {
  }

  return new WebServer();
}

src/mocks/UserMockEndpoint.js

By creating files with the ending name of *MockEndPoint.js, it will self register as a mock controller. You can have multiple MockEndpoint files, as long as they don't share the same endpoint urls.

You can also have multiple request handlers in the same MockEndpoint and change which loads dynamically.

module.exports = function (MockEndpoint) {

  class UserMockEndpoint extends MockEndpoint {
    method() {
      return MockEndpoint.METHODS.GET;
    }

    url() {
      return '/user/:id';
    }

    default(req, res, next) {
      const userId = parseInt(req.params.id);
      const user = {
        id: userId,
        name: "User Name",
        statusCode: 200
      };

      res.status(user.statusCode).json(user);
    }
  }

  return new UserMockEndpoint();
};

start.js

const injector = require('./src/injector');

injector().inject(function (WebServer) {
  // Starts the web server by loading all the default methods in the MockEndPoints
  WebServer.startWithDefaults();
});

Mixed web app usage example

While you can have a standalone mock server, sometimes it's needed to use mock endpoints in an actual application. This scenario could be due to the need to be able to work on parts of the REST API that are defined and mock out parts that are not completely defined.

The following examples show how you mix them by adding a few calls to your web server app based on BaseWebServer defined in Spur-Web. For it's full configuration, take a look at the documentation in Spur-Web, but the following are a highlight of the dependency configuration needed to make it work.

src/injector.js

const path = require('path');
const spur = require('spur-ioc');
const spurCommon = require('spur-common');
const spurWeb = require('spur-web');
const spurMockserver = require('spur-mockserver');
const spurConfig = require('spur-config');
const registerConfig = require('spur-common/registerConfig');

module.exports = function () {
  const ioc = spur.create('spur-mockserver-example');

  // ... other dependencies

  ioc.merge(spurMockserver());

  ioc.registerFolders(__dirname, [
    'mocks'
    'runtime'
  ]);

  return ioc;
};

src/runtime/WebServer.js

module.exports = function (BaseWebServer, config) {

  class MockWebServer extends BaseWebServer {
    constructor() {
      super();
      this.useDefaults = config.useMockDefaults;
    }

    registerMiddleware() {
      super.registerMiddleware();
      this.registerMockEndpoints();
    }

    registerMockEndpoints() {
      Logger.log(`Attempting to register mock-endpoints - Use Defaults (${this.useDefaults})`);
      MockEndpointRegistration.register(this.app, this, this.useDefaults);
    }

    setUseDefaults(useDefaults = false) {
      this.useDefaults = useDefaults;
    }

    startWithDefaults() {
      this.setUseDefaults(true)
      return this.start();
    }
  }

  return new MockWebServer();
};

Controlling fixtures from a browser client

The /v3/fixtures middleware handler enables the customization of fixtures returned by mock endpoints from web browser clients, e.g. with XMLHttpRequest or fetch, addressing use cases of web UI developers and manual QA.

Method

const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/v3/fixtures');
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.send(JSON.stringify({
  fixtures: [{
    endpoint: 'MyMockEndpoint',
    method: 'myMethod'
  }]
}));

If the mock server is running on localhost and the mock endpoint MyMockEndpoint is registered and has a method myMethod, the POST request succeeds and successive requests that are handled by MyMockEndpoint will run myMethod to generate its response.

JSON

const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/v3/fixtures');
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.send(JSON.stringify({
  fixtures: [{
    endpoint: 'MyMockEndpoint',
    json: { 'example':[1, 2, 3] }
  }]
}));

If the mock server is running on localhost and the mock endpoint MyMockEndpoint is registered, the POST request succeeds and successive requests that are handled by MyMockEndpoint will respond with an HTTP status of 200 and the JSON {"example":[1, 2, 3]}.

Contributing

We accept pull requests

Please send in pull requests and they will be reviewed in a timely manner. Please review this generic guide to submitting a good pull requests. The only things we ask in addition are the following:

  • Please submit small pull requests
  • Provide a good description of the changes
  • Code changes must include tests
  • Be nice to each other in comments. :innocent:

Style guide

The majority of the settings are controlled using an EditorConfig configuration file. To use it please download a plugin for your editor of choice.

All tests should pass

To run the test suite, first install the dependancies, then run npm test

$ npm install
$ npm test

License

MIT