Node Packaged Modules (npm)

npm contains the following modules:

  • mockserver-node - node module and grunt tasks to start and stop MockServer and its proxy  npm version 
  • mockserver-client - node client for MockServer and its proxy  npm version 

Running MockServer With mockserver-node

The node module can be used to start and stop MockServer as a node module or as a Grunt plugin.

You may install this plugin / node module with the following command:

npm install mockserver-node --save-dev

Node Module

To start or stop the MockServer from any Node.js code you need to import this module using require('mockserver-node') as follows:

var mockserver = require('mockserver-node');

Then you can use either the start_mockserver or stop_mockserver functions as follows:

var mockserver = require('mockserver-node');
mockserver.start_mockserver({
                serverPort: 1080,
                verbose: true,
                trace: true
            });

// do something

mockserver.stop_mockserver({
                serverPort: 1080
            });

You can customize the JVM arguments and set configuration options as follows

var mockserver = require('mockserver-node');
mockserver.start_mockserver({
              serverPort: 1080,
              jvmOptions: [
                  '-Dmockserver.enableCORSForAllResponses=true',
                  '-Dmockserver.corsAllowMethods="CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH, TRACE"',
                  '-Dmockserver.corsAllowHeaders="Allow, Content-Encoding, Content-Length, Content-Type, ETag, Expires, Last-Modified, Location, Server, Vary, Authorization"',
                  '-Dmockserver.corsAllowCredentials=true',
                  '-Dmockserver.corsMaxAgeInSeconds=300'
              ],
              mockServerVersion: "9.2.0",
              verbose: true
          });

MockServer uses port unification to support HTTP, HTTPS, SOCKS, HTTP CONNECT, Port Forwarding Proxying on the same port. A client can then connect to the single port with both HTTP and HTTPS as the socket will automatically detected SSL traffic and decrypt it when required.

Requirements

start_mockserver runs MockServer with the java command, so Java 17 or later must be installed and its bin directory must be on the PATH of the Node.js process. JAVA_HOME is not used, and there is no option for the location of java.

When a start fails

start_mockserver returns a promise. It is rejected with an Error, and the same message is printed to stderr, when:

  • there is no java on the PATH (error.code is ENOENT), or the one found cannot be run (EACCES): the message says where java was looked for
  • java exits with a failing status, or is ended by a signal, before MockServer is ready, for example when jvmOptions holds an option it does not accept: the start fails at once and the message ends with the last lines the process printed
  • MockServer does not become ready in the time startupRetries allows

A failed start never ends the calling process, and leaves it free to carry on or to exit (unless a JVM was left waiting for a debugger, see javaDebugPort). Handle the rejection to fail your own script, and call stop_mockserver afterwards if you wish: it resolves when nothing is running.

mockserver.start_mockserver({serverPort: 1080}).then(function () {
    // MockServer is ready
}, function (error) {
    process.exitCode = 1;
});

TypeScript

TypeScript typings for mockserver-node are published in the npm package. They use Node's own types, so your project needs @types/node installed. Both import mockserver = require('mockserver-node') and import * as mockserver from 'mockserver-node' work with or without esModuleInterop; a default import (import mockserver from 'mockserver-node') needs esModuleInterop turned on and is otherwise a compile error.

Note: the package declares an exports map, naming index, downloadJar, downloadBinary and package.json. A deep import of a path it doesn't name — for example mockserver-node/tasks/mockServer.js — now fails with ERR_PACKAGE_PATH_NOT_EXPORTED, where previously any file inside the package could be required.

Grunt Plugin

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins.

In your project's Gruntfile, add a section named start_mockserver and stop_mockserver to the data object passed into grunt.initConfig().

The following example starts a MockServer on port 1080 (with a matching task to stop it again).

grunt.initConfig({
    start_mockserver: {
        start: {
            options: {
                serverPort: 1080,
                trace: true
            }
        }
    },
    stop_mockserver: {
        stop: {
            options: {
                serverPort: 1080
            }
        }
    }
});

grunt.loadNpmTasks('mockserver-node');

Request Log

The request log will only be captured in MockServer if the log level is INFO (or more verbose, i.e. DEBUG or TRACE) therefore to capture the request log and use the /retrieve endpoint ensure either the option trace: true or the command line switch --verbose is set.

Grunt Plugin & NPM Module Options

options.serverPort

Type: Integer Default: undefined

The HTTP, HTTPS, SOCKS and HTTP CONNECT port(s) for both mocking and proxying requests. Port unification is used to support all protocols for proxying and mocking on the same port(s). Supports comma separated list for binding to multiple ports.

options.proxyRemotePort

Type: Integer Default: undefined

Optionally enables port forwarding mode. When specified all requests received will be forwarded to the specified port, unless they match an expectation.

options.proxyRemoteHost

Type: String Default: undefined

Specified the host to forward all proxy requests to when port forwarding mode has been enabled using the proxyRemotePort option. This setting is ignored unless proxyRemotePort has been specified. If no value is provided for proxyRemoteHost when proxyRemotePort has been specified, proxyRemoteHost will default to "localhost".

options.artifactoryHost

Type: String Default: oss.sonatype.org

This value specifies the name of the artifact repository host.

options.artifactoryPath

Type: String Default: /content/repositories/releases/org/mock-server/mockserver-netty/

This value specifies the path to the artifactory leading to the mockserver-netty jar with dependencies.

options.mockServerVersion

Type: String Default: 9.2.0

This value specifies the artifact version of MockServer to download.

Note: It is also possible to specify a SNAPSHOT version to get the latest unreleased changes.

Note: The jar is downloaded once and kept inside the installed mockserver-node module itself (i.e. node_modules/mockserver-node), not in the directory you run from, so it is re-used no matter where you start MockServer from and is removed when the module is uninstalled. Jars for different versions are kept side by side, so switching between versions does not re-download them; a SNAPSHOT version is always re-fetched, since its contents change without its version changing. If that directory is not writable — for example a global install owned by root but used by another user, or a read-only container layer — the jar is downloaded into the directory you run from instead.

Note: A download that receives nothing at all for 60 seconds is abandoned with an error rather than waiting indefinitely. A slow download is never interrupted, only a silent one, but if you are behind a proxy that pauses for longer than this before it starts sending, set the MOCKSERVER_DOWNLOAD_IDLE_TIMEOUT_MILLIS environment variable to a larger number of milliseconds.

options.verbose

Type: Boolean Default: false

This value indicates whether the MockServer logs should be written to the console. In addition to logging additional output from the grunt task this options also sets the logging level of the MockServer to INFO. At INFO level all interactions with the MockServer including setting up expectations, matching expectations, clearing expectations and verifying requests are written to the log.

Note: It is also possible to use the --verbose command line switch to enabled verbose level logging from the command line.

options.trace

Type: Boolean Default: false

This value sets the logging level of the MockServer to TRACE. At TRACE level (in addition to INFO level information) all matcher results, including when specific matchers fail (such as HeaderMatcher) are written to the log.

options.javaDebugPort

Type: Integer Default: undefined

This value indicates whether Java debugging should be enabled and if so which port the debugger should listen on. When this options is provided the following additional option is passed to the JVM:

"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + javaDebugPort

Note: suspend=y is used so the MockServer will pause until the debugger is attached. The grunt task will wait 50 seconds for the debugger to be attached before it exits with a failure status. The paused JVM is left running when that happens, so a debugger can still be attached to it; stop it yourself when you are done.

options.runForked

Type: Boolean Default: false

If the calling process meets an uncaught exception, the MockServer it launched is ended so that it is not left running once the process has gone. The exception itself is left alone: Node.js reports it and exits with a failing status, or your own uncaughtException handler deals with it. The server is ended even when your own handler, or a test runner, deals with the exception and the process carries on. Only the java process the launcher started is signalled: if the java on your PATH is a wrapper script that does not exec the JVM, the JVM is left running. Set this option to true to leave MockServer running instead.

options.jvmOptions

Type: String Default: undefined

This value allows any system properties to be passed to the JVM that runs MockServer, for example:

start_mockserver: {
    options: {
        serverPort: 1080,
        jvmOptions: "-Dmockserver.enableCORSForAllResponses=true"
    }
}

options.startupRetries

Type: Integer Default: if javaDebugPort is not set 110, but if javaDebugPort is set 500

This value indicates the how many times we will call the check to confirm if the mock server started up correctly. It will default to 110 which will take about 11 seconds to complete, this is normally long enough for the server to startup. The server can take longer to start up if Java debugging is enabled so this will default to 500. The default will, in some cases, need to be overridden as the JVM may take longer to start up on some architectures, e.g. Mac seems to take a little longer.

The checks are 100 milliseconds apart, and each one waits up to 2 seconds for an answer. A check that gets no answer in that time uses up 20 further retries, so a server that accepts connections and never answers makes the start give up after about startupRetries × 100 milliseconds plus 2 seconds, much as one that refuses connections does. When the start gives up it fails with a message saying so and stops the JVM it launched, unless javaDebugPort is set.