Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface Mockttp

A mockttp instance allow you to start and stop mock servers and control their behaviour.

This should be created using the exported getLocal or getRemote methods, like so:

const mockServer = require('mockttp').getLocal()

Call .start() to set up a server on a random port, use .forX methods like .forGet(url), .forPost(url) and .forAnyRequest() to get a RequestRuleBuilder and start defining mock rules. You can also mock WebSocket requests using .forAnyWebSocket(). Call .stop() when your test is complete. An example:

await mockServer.start();
await mockServer.forGet('/abc').thenReply(200, "a response");
// ...Make some requests
await mockServer.stop();

Hierarchy

  • Mockttp

Implemented by

Index

Metadata Properties

port: number

The port the server is running on.

This will throw an error if read before the server is started.

proxyEnv: ProxyEnvConfig

The environment variables typically needed to use this server as a proxy, in a format you can add to your environment straight away.

This will throw an error if read before the server is started.

process.env = Object.assign(process.env, mockServer.proxyEnv)
url: string

The root URL of the server.

This will throw an error if read before the server is started.

Events Methods

  • on(event: "request-initiated", callback: ((req: Request) => void)): Promise<void>
  • on(event: "request", callback: ((req: CompletedRequest) => void)): Promise<void>
  • on(event: "response", callback: ((req: CompletedResponse) => void)): Promise<void>
  • on(event: "websocket-request", callback: ((req: CompletedRequest) => void)): Promise<void>
  • on(event: "websocket-accepted", callback: ((req: CompletedResponse) => void)): Promise<void>
  • on(event: "websocket-message-received", callback: ((req: WebSocketMessage) => void)): Promise<void>
  • on(event: "websocket-message-sent", callback: ((req: WebSocketMessage) => void)): Promise<void>
  • on(event: "websocket-close", callback: ((req: WebSocketClose) => void)): Promise<void>
  • on(event: "abort", callback: ((req: AbortedRequest) => void)): Promise<void>
  • on(event: "tls-passthrough-opened", callback: ((req: TlsPassthroughEvent) => void)): Promise<void>
  • on(event: "tls-passthrough-closed", callback: ((req: TlsPassthroughEvent) => void)): Promise<void>
  • on(event: "tls-client-error", callback: ((req: TlsRequest) => void)): Promise<void>
  • on(event: "client-error", callback: ((error: ClientError) => void)): Promise<void>
  • on<T>(event: "rule-event", callback: ((event: RuleEvent<T>) => void)): Promise<void>
  • Subscribe to hear about request details as soon as the initial request details (method, path & headers) are received, without waiting for the body.

    This is only useful in some niche use cases, such as logging all requests seen by the server independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    • event: "request-initiated"
    • callback: ((req: Request) => void)

    Returns Promise<void>

  • Subscribe to hear about request details once the request is fully received.

    This is only useful in some niche use cases, such as logging all requests seen by the server independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about response details when the response is completed.

    This is only useful in some niche use cases, such as logging all requests seen by the server independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about websocket connection requests. This event fires when the initial WebSocket request is completed, regardless of whether the request is accepted.

    This is only useful in some niche use cases, such as logging all websockets seen by the server independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about websocket connection upgrades. This event fires when a WebSocket request is accepted, returning the HTTP response body that was sent before the WebSocket stream starts.

    This is only useful in some niche use cases, such as logging all websockets seen by the server independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about websocket messages received by Mockttp from its downstream websocket clients. This event fires whenever any data is received on an open mocked WebSocket.

    This is only useful in some niche use cases, such as logging all websockets seen by the server independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about websocket messages sent by Mockttp to its downstream websocket clients. This event fires whenever any data is sent on an open mocked WebSocket.

    This is only useful in some niche use cases, such as logging all websockets seen by the server independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear when a websocket connection is closed. This fires only for clean websocket shutdowns, after the websocket was initially accepted. If the connection is closed uncleanly, an 'abort' event will fire instead. If the websocket was initially rejected explicitly, a 'response' event (with the rejecting response) will fire instead.

    This is only useful in some niche use cases, such as logging all websockets seen by the server independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about requests that are aborted before the request or response is fully completed.

    This is only useful in some niche use cases, such as logging all requests seen by the server independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about TLS connections that are passed through the proxy without interception, due to the tlsPassthrough HTTPS option.

    This is only useful in some niche use cases, such as logging all requests seen by the server, independently of the rules defined.

    The callback will be called asynchronously from connection handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about closure of TLS connections that were passed through the proxy without interception, due to the tlsPassthrough HTTPS option.

    This is only useful in some niche use cases, such as logging all requests seen by the server, independently of the rules defined.

    The callback will be called asynchronously from connection handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about requests that start a TLS handshake, but fail to complete it. Not all clients report TLS errors explicitly, so this event fires for explicitly reported TLS errors, and for TLS connections that are immediately closed with no data sent.

    This is typically useful to detect clients who aren't correctly configured to trust the configured HTTPS certificate. The callback is given the host name provided by the client via SNI, if SNI was used (it almost always is).

    This is only useful in some niche use cases, such as logging all requests seen by the server, independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Subscribe to hear about requests that fail before successfully sending their initial parameters (the request line & headers). This will fire for requests that drop connections early, send invalid or too-long headers, or aren't correctly parseable in some form.

    This is typically useful to detect clients who aren't correctly configured. The callback is given an object containing the request (as we were best able to parse it) and either the error response returned, or 'aborted' if the connection was disconnected before the server could respond.

    This is only useful in some niche use cases, such as logging all requests seen by the server, independently of the rules defined.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Parameters

    Returns Promise<void>

  • Some rules may emit events with metadata about request processing. For example, passthrough rules may emit events about upstream server interactions.

    You can listen to rule-event to hear about all these events. When emitted, this will include the id of the request being processed, the id of the rule that fired the event, the type of the event, and the event data itself.

    This is only useful in some niche use cases, such as logging all proxied upstream requests made by the server, separately from the client connections handled.

    The callback will be called asynchronously from request handling. This function returns a promise, and the callback is not guaranteed to be registered until the promise is resolved.

    Type Parameters

    • T = unknown

    Parameters

    Returns Promise<void>

Manual rule definition Methods

  • Adds the given HTTP request rule to the server.

    This is a convenient alias for calling addRequestRules with one rule, and extracting the first endpoint result.

    This API is only useful if you're manually building rules, rather than using RequestRuleBuilder, and is only for special cases. This approach may be necessary if you need to configure all your rules in one place to enable them elsewhere/later.

    Parameters

    Returns Promise<MockedEndpoint>

  • Adds the given HTTP request rules to the server.

    This API is only useful if you're manually building rules, rather than using RequestRuleBuilder, and is only for special cases. This approach may be necessary if you need to configure all your rules in one place to enable them elsewhere/later.

    Parameters

    Returns Promise<MockedEndpoint[]>

  • Adds the given websocket rule to the server.

    This is a convenient alias for calling addWebSocketRules with one rule, and extracting the first endpoint result.

    This API is only useful if you're manually building rules, rather than using RequestRuleBuilder, and is only for special cases. This approach may be necessary if you need to configure all your rules in one place to enable them elsewhere/later.

    Parameters

    Returns Promise<MockedEndpoint>

  • Adds the given websocket rules to the server.

    This API is only useful if you're manually building rules, rather than using RequestRuleBuilder, and is only for special cases. This approach may be necessary if you need to configure all your rules in one place to enable them elsewhere/later.

    Parameters

    Returns Promise<MockedEndpoint[]>

  • Set the given HTTP request rules as the only request rules on the server, replacing any existing rules (except websocket rules).

    This API is only useful if you're manually building rules, rather than using RequestRuleBuilder, and is only for special cases. This approach may be necessary if you need to configure all your rules in one place to enable them elsewhere/later.

    Parameters

    Returns Promise<MockedEndpoint[]>

  • Set the given websocket rules as the only websocket rules on the server, replacing all existing websocket rules (but leaving normal rules untouched).

    This API is only useful if you're manually building rules, rather than using RequestRuleBuilder, and is only for special cases. This approach may be necessary if you need to configure all your rules in one place to enable them elsewhere/later.

    Parameters

    Returns Promise<MockedEndpoint[]>

Metadata Methods

  • Returns the set of registered but pending mock endpoints: endpoints which either haven't seen the specified number of requests (if one was specified e.g. with .twice()) or which haven't seen at least one request, by default.

    Returns Promise<MockedEndpoint[]>

  • getRuleParameterKeys(): Promise<string[]>
  • List the names of the rule parameters available for rule definitions. These parameters are defined by the admin server. This list can be used in some advanced use cases to confirm beforehand that the parameters a client wishes to reference are available.

    Only relevant to remote/browser Mockttp usage. Servers created directly without any admin server will never have rule parameters defined, and so this method will always return an empty list.

    Returns Promise<string[]>

  • urlFor(path: string): string
  • The URL for a given path on the server.

    This will throw an error if read before the server is started.

    Parameters

    • path: string

    Returns string

Mock HTTP requests Methods

  • Get a builder for a mock rule that will match any requests on any path.

    This only matches traditional HTTP requests, not websockets, which are handled separately. To match websockets, use .forAnyWebSocket().

    Returns RequestRuleBuilder

  • Get a builder for a mock rule that will match DELETE requests for the given path. If no path is specified, this matches all DELETE requests.

    The path can be either a string, or a regular expression to match against. Path matching always ignores query parameters. To match query parameters, use .withQuery({ a: 'b' }) or withExactQuery('?a=b').

    There are a few supported matching formats:

    • Relative string paths (/abc) will be compared only to the request's path, independent of the host & protocol, ignoring query params.
    • Absolute string paths with no protocol (localhost:8000/abc) will be compared to the URL independent of the protocol, ignoring query params.
    • Fully absolute string paths (http://localhost:8000/abc) will be compared to entire URL, ignoring query params.
    • Regular expressions can match the absolute URL: /^http:\/\/localhost:8000\/abc$/
    • Regular expressions can also match the path: /^\/abc/

    Parameters

    • Optional url: string | RegExp

    Returns RequestRuleBuilder

  • Get a builder for a mock rule that will match GET requests for the given path. If no path is specified, this matches all GET requests.

    The path can be either a string, or a regular expression to match against. Path matching always ignores query parameters. To match query parameters, use .withQuery({ a: 'b' }) or withExactQuery('?a=b').

    There are a few supported matching formats:

    • Relative string paths (/abc) will be compared only to the request's path, independent of the host & protocol, ignoring query params.
    • Absolute string paths with no protocol (localhost:8000/abc) will be compared to the URL independent of the protocol, ignoring query params.
    • Fully absolute string paths (http://localhost:8000/abc) will be compared to entire URL, ignoring query params.
    • Regular expressions can match the absolute URL: /^http:\/\/localhost:8000\/abc$/
    • Regular expressions can also match the path: /^\/abc/

    Parameters

    • Optional url: string | RegExp

    Returns RequestRuleBuilder

  • Get a builder for a mock rule that will match HEAD requests for the given path. If no path is specified, this matches all HEAD requests.

    The path can be either a string, or a regular expression to match against. Path matching always ignores query parameters. To match query parameters, use .withQuery({ a: 'b' }) or withExactQuery('?a=b').

    There are a few supported matching formats:

    • Relative string paths (/abc) will be compared only to the request's path, independent of the host & protocol, ignoring query params.
    • Absolute string paths with no protocol (localhost:8000/abc) will be compared to the URL independent of the protocol, ignoring query params.
    • Fully absolute string paths (http://localhost:8000/abc) will be compared to entire URL, ignoring query params.
    • Regular expressions can match the absolute URL: /^http:\/\/localhost:8000\/abc$/
    • Regular expressions can also match the path: /^\/abc/

    Parameters

    • Optional url: string | RegExp

    Returns RequestRuleBuilder

  • Match JSON-RPC requests, optionally matching a given method and/or params.

    If no method or params are specified, this will match all JSON-RPC requests.

    Params are matched flexibly, using the same logic as .withJsonBodyIncluding(), so only the included fields are checked and other extra fields are ignored

    Parameters

    • Optional match: { method?: string; params?: any }
      • Optional method?: string
      • Optional params?: any

    Returns RequestRuleBuilder

  • Get a builder for a mock rule that will match OPTIONS requests for the given path.

    The path can be either a string, or a regular expression to match against. Path matching always ignores query parameters. To match query parameters, use .withQuery({ a: 'b' }) or withExactQuery('?a=b').

    There are a few supported matching formats:

    • Relative string paths (/abc) will be compared only to the request's path, independent of the host & protocol, ignoring query params.
    • Absolute string paths with no protocol (localhost:8000/abc) will be compared to the URL independent of the protocol, ignoring query params.
    • Fully absolute string paths (http://localhost:8000/abc) will be compared to entire URL, ignoring query params.
    • Regular expressions can match the absolute URL: /^http:\/\/localhost:8000\/abc$/
    • Regular expressions can also match the path: /^\/abc/

    This can only be used if the cors option has been set to false.

    If cors is true (the default when using a remote client, e.g. in the browser), then the mock server automatically handles OPTIONS requests to ensure requests to the server are allowed by clients observing CORS rules.

    You can pass {cors: false} to getLocal/getRemote to disable this behaviour, but if you're testing in a browser you will need to ensure you mock all OPTIONS requests appropriately so that the browser allows your other requests to be sent.

    Parameters

    • Optional url: string | RegExp

    Returns RequestRuleBuilder

  • Get a builder for a mock rule that will match PATCH requests for the given path. If no path is specified, this matches all PATCH requests.

    The path can be either a string, or a regular expression to match against. Path matching always ignores query parameters. To match query parameters, use .withQuery({ a: 'b' }) or withExactQuery('?a=b').

    There are a few supported matching formats:

    • Relative string paths (/abc) will be compared only to the request's path, independent of the host & protocol, ignoring query params.
    • Absolute string paths with no protocol (localhost:8000/abc) will be compared to the URL independent of the protocol, ignoring query params.
    • Fully absolute string paths (http://localhost:8000/abc) will be compared to entire URL, ignoring query params.
    • Regular expressions can match the absolute URL: /^http:\/\/localhost:8000\/abc$/
    • Regular expressions can also match the path: /^\/abc/

    Parameters

    • Optional url: string | RegExp

    Returns RequestRuleBuilder

  • Get a builder for a mock rule that will match POST requests for the given path. If no path is specified, this matches all POST requests.

    The path can be either a string, or a regular expression to match against. Path matching always ignores query parameters. To match query parameters, use .withQuery({ a: 'b' }) or withExactQuery('?a=b').

    There are a few supported matching formats:

    • Relative string paths (/abc) will be compared only to the request's path, independent of the host & protocol, ignoring query params.
    • Absolute string paths with no protocol (localhost:8000/abc) will be compared to the URL independent of the protocol, ignoring query params.
    • Fully absolute string paths (http://localhost:8000/abc) will be compared to entire URL, ignoring query params.
    • Regular expressions can match the absolute URL: /^http:\/\/localhost:8000\/abc$/
    • Regular expressions can also match the path: /^\/abc/

    Parameters

    • Optional url: string | RegExp

    Returns RequestRuleBuilder

  • Get a builder for a mock rule that will match PUT requests for the given path. If no path is specified, this matches all PUT requests.

    The path can be either a string, or a regular expression to match against. Path matching always ignores query parameters. To match query parameters, use .withQuery({ a: 'b' }) or withExactQuery('?a=b').

    There are a few supported matching formats:

    • Relative string paths (/abc) will be compared only to the request's path, independent of the host & protocol, ignoring query params.
    • Absolute string paths with no protocol (localhost:8000/abc) will be compared to the URL independent of the protocol, ignoring query params.
    • Fully absolute string paths (http://localhost:8000/abc) will be compared to entire URL, ignoring query params.
    • Regular expressions can match the absolute URL: /^http:\/\/localhost:8000\/abc$/
    • Regular expressions can also match the path: /^\/abc/

    Parameters

    • Optional url: string | RegExp

    Returns RequestRuleBuilder

  • Get a builder for a fallback mock rule that will match any unmatched requests on any path.

    Fallback rules act like any other rule, but they only match if there is no existing normal rule that matches the request, or if all existing rules have an explicit execution limit (like once()) that has been completed.

    Returns RequestRuleBuilder

Mock websockets Methods

Setup Methods

  • enableDebug(): void
  • Enable extra debug output so you can understand exactly what the server is doing.

    Returns void

  • reset(): void
  • Reset the stored rules and subscriptions. Most of the time it's better to start & stop the server instead, but this can be useful in some special cases.

    Returns void

  • start(port?: number | PortRange): Promise<void>
  • Start a mock server.

    Specify a fixed port if you need one.

    If you don't, a random port will be chosen, which you can get later with .port, or by using .url and .urlFor(path) to generate your URLs automatically.

    If you need to allow port selection, but in a specific range, pass a { startPort, endPort } pair to define the allowed (inclusive) range.

    Parameters

    Returns Promise<void>

  • stop(): Promise<void>
  • Stop the mock server and reset all rules and subscriptions.

    Returns Promise<void>

Generated using TypeDoc