Skip to content

Latest commit

 

History

History

README.md

mockserver-client-node

Communicate with a MockServer from any node or grunt build

Build status

NPM

Community

  • Roadmap:                     GitHub Project
  • Feature Requests:   Github Issues
  • Issues / Bugs:           Github Issues
  • Discussions:               GitHub Discussions

Getting Started

MockServer allows you to mock any system you integrate with via HTTP or HTTPS (i.e. (REST) services, web sites, etc). Please note that it is a third party project that needs java.

This npm module allows any grunt or node project to easily communicate with a running MockServer instance.

As an addition to this module for communicating with a running MockServer there is a second project that can be used to start and stop a MockServer called mockserver-node.

The MockServer client can be created as follows:

var mockServer = require('mockserver-client'),
    mockServerClient = mockServer.mockServerClient // MockServer and proxy client

Note: this assumes you have an instance of MockServer running on port 1080. For more information on how to do so check mockserver-node.

Setup Expectation

A simple expectation can be set up as follows:

mockServerClient("localhost", 1080)
    .mockSimpleResponse('/somePath', { name: 'value' }, 203)
    .then(
        function(result) {
            // do something next
        }, 
        function(error) {
            // handle error
        }
    );

A more complex expectation can be set up like this:

mockServerClient("localhost", 1080)
    .mockAnyResponse(
        {
            'httpRequest': {
                'method': 'POST',
                'path': '/somePath',
                'queryStringParameters': [
                    {
                        'name': 'test',
                        'values': [ 'true' ]
                    }
                ],
                'body': {
                    'type': "STRING",
                    'value': 'someBody'
                }
            },
            'httpResponse': {
                'statusCode': 200,
                'body': JSON.stringify({ name: 'value' }),
                'delay': {
                    'timeUnit': 'MILLISECONDS',
                    'value': 250
                }
            },
            'times': {
                'remainingTimes': 1,
                'unlimited': false
            }
        }
    )
    .then(
        function(result) {
            // do something next
        }, 
        function(error) {
            // handle error
        }
    );

For the full documentation see MockServer - Creating Expectations.

Verify Requests

It is also possible to verify that request were made:

mockServerClient("localhost", 1080)
    .verify(
        {
            'method': 'POST',
            'path': '/somePath',
            'body': 'someBody'
        }, 
        1, true
    )
    .then(
        function() {
            // do something next
        }, 
        function(failure) {
            // handle verification failure
        }
    );

It is furthermore possible to verify that sequences of requests were made in a specific order:

mockServerClient("localhost", 1080)
    .verifySequence(
        {
            'method': 'POST',
            'path': '/somePathOne',
            'body': 'someBody'
        },
        {
            'method': 'GET',
            'path': '/somePathTwo'
        },
        {
            'method': 'GET',
            'path': '/somePathThree'
        }
    )
    .then(
        function() {
            // do something next
        }, 
        function(failure) {
            // handle verification failure
        }
    );

For the full documentation see MockServer - Verifying Requests.

Interactive Breakpoints

The client supports matcher-driven interactive breakpoints over the callback WebSocket. Register a breakpoint matcher to pause forwarded/proxied exchanges at specific phases and inspect/modify/continue them via callback handlers.

Register a breakpoint

// REQUEST phase only
client.addRequestBreakpoint(
    { path: '/api/.*' },
    function (request) {
        // inspect or modify the request; return a request to continue or a response to abort
        request.path = '/api/modified';
        return request;
    }
).then(function (breakpointId) {
    console.log('Breakpoint registered:', breakpointId);
});

// REQUEST + RESPONSE phases
client.addRequestAndResponseBreakpoint(
    { path: '/api/.*' },
    function (request) { return request; },           // REQUEST handler
    function (request, response) { return response; } // RESPONSE handler
).then(function (breakpointId) {
    console.log('Breakpoint registered:', breakpointId);
});

// All phases with stream frame handler
client.addBreakpoint(
    { path: '/stream/.*' },
    ['REQUEST', 'RESPONSE', 'RESPONSE_STREAM', 'INBOUND_STREAM'],
    function (request) { return request; },
    function (request, response) { return response; },
    function (pausedFrame) {
        // pausedFrame has: correlationId, streamId, sequenceNumber, direction, phase, body (base64)
        return { action: 'CONTINUE' };
        // Other actions: MODIFY (with body), DROP, INJECT (with body), CLOSE
    }
).then(function (breakpointId) {
    console.log('Breakpoint registered:', breakpointId);
});

Manage breakpoints

// List all matchers
client.listBreakpointMatchers().then(function (result) {
    console.log(result.matchers);
});

// Remove a specific matcher
client.removeBreakpointMatcher(breakpointId);

// Clear all matchers
client.clearBreakpointMatchers();

Start / Launch MockServer

This package (mockserver-client) is the REST/WebSocket client for communicating with a running MockServer. To download and launch a local MockServer instance (no Java or Docker required), use the companion mockserver-node package:

npx -p mockserver-node mockserver run -p 1080

mockserver-node downloads a self-contained platform bundle (mockserver-<version>-<os>-<arch>) from the GitHub Release, verifies its SHA-256, caches it per-user, and starts it. See the mockserver-node README for full details including environment variables (MOCKSERVER_BINARY_BASE_URL, MOCKSERVER_BINARY_CACHE, MOCKSERVER_SKIP_BINARY_DOWNLOAD) and supported platforms (linux/darwin/windows on x86_64/aarch64).

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.

Changelog

All notable and significant changes are detailed in the MockServer changelog


Task submitted by James D Bloom

AI Assistant Integration

MockServer includes a built-in MCP (Model Context Protocol) server that enables AI coding assistants to create expectations, verify requests, and debug HTTP traffic programmatically.