Subscribe to hear when a mock session is stopped. The listener is provided with +the state of all plugins that are about to be stopped. This can be used to log +mock session shutdown, add side-effects that run elsewhere at shutdown, or clean +up after sessions in other ways.
+This is run synchronously immediately before the session is shutdown, whilst all
+its state is still available, and before remote clients have had any response to
+their request. This is also run before shutdown when the admin server itself is
+cleanly shutdown with adminServer.stop()
.
A in-process Mockttp implementation. This starts servers on the local machine in the +current process, and exposes methods to directly manage them.
+This class does not work in browsers, as it expects to be able to start HTTP servers.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+Rest
...ruleData: RequestRuleData[]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.
+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.
+Rest
...ruleData: WebSocketRuleData[]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.
+Rest
...ruleData: RequestRuleData[]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.
+Rest
...ruleData: WebSocketRuleData[]The port the server is running on.
+This will throw an error if read before the server is started.
+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)
+
+
+The root URL of the server.
+This will throw an error if read before the server is started.
+Returns the set of currently registered mock endpoints.
+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.
+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.
+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()
.
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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpMatch 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
+Optional
method?: stringOptional
params?: anyGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/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.
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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.
Get a builder for a mock rule that will match all websocket connections.
+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.
+A bare admin server client. This is not intended for general use, but can be useful when +building admin server plugins to mock non-HTTP protocols and other advanced use cases.
+For normal usage of Mockttp, you should use Mockttp.getRemote()
instead, to get a Mockttp
+remote client, which wraps this class with the full Mockttp API for mocking HTTP.
This is part of Mockttp's experimental 'pluggable admin' API. It may change +unpredictably, even in minor releases.
+Rest
...queries: [...Queries[]]Subscribe to hear when each mock ession is started. The listener is provided the +session plugin data, which can be used to log session startup, add side-effects that +run elsewhere at startup, or preconfigure every started plugin in addition ways.
+This is run synchronously when a session is created, after it has fully started +but before its been returned to remote clients.
+Subscribe to hear when a mock session is stopped. The listener is provided with +the state of all plugins that are about to be stopped. This can be used to log +mock session shutdown, add side-effects that run elsewhere at shutdown, or clean +up after sessions in other ways.
+This is run synchronously immediately before the session is shutdown, whilst all
+its state is still available, and before remote clients have had any response to
+their request. This is also run before shutdown when the admin server itself is
+cleanly shutdown with adminServer.stop()
.
Optional
topicId: stringAbstract
Optional
emitOptional
emitOptional
record?: booleanRequestRuleBuilder
+A builder for defining mock rules. Create one using a method like
+.forGet(path)
or .forPost(path)
on a Mockttp instance, then call
+whatever methods you'd like here to define more precise request
+matching behaviour, control how the request is handled, and how
+many times this rule should be applied.
When you're done, call a .thenX()
method to register the configured rule
+with the server. These return a promise for a MockedEndpoint, which can be
+used to verify the details of the requests matched by the rule.
This returns a promise because rule registration can be asynchronous,
+either when using a remote server or testing in the browser. Wait for the
+promise returned by .thenX()
methods to guarantee that the rule has taken
+effect before sending requests to it.
Match only requests sent to the given host, i.e. the full hostname plus +port included in the request.
+This can behave somewhat confusingly when matching against the default +ports for a protocol (i.e. 80/443), or when specifying a hostname here +without specifying the port. In those cases it's usually better to use +forHostname and/or forPort instead to explicit match the content you're +interested in.
+Match only requests when the callback returns true
+Match only requests whose bodies match (contain equivalent +values, ignoring extra values) the given object, when +parsed as JSON. Matching behaviour is the same as Lodash's +_.isMatch method.
+Note that this only tests that the body can be parsed +as JSON - it doesn't require a content-type header.
+Match only requests whose bodies include the given multipart form data.
+This can take any number of form parts to look for. Each part is specified
+with MultipartFieldMatchCondition object containing one or more of
+name
(string), filename
(string) and content
(string or buffer) as
+fields to match against in the form data.
Requests are matched if all conditions match at least one part in the +request's form data.
+Rest
...matchConditions: MultipartFieldMatchCondition[]Mock rule builders should be constructed through the Mockttp instance you're +using, not directly. You shouldn't ever need to call this constructor.
+Set the rule priority. Any matching rule with a higher priority will always
+take precedence over a matching lower-priority rule, unless the higher rule
+has an explicit completion check (like .once()
) that has already been
+completed.
The RulePriority enum defines the standard values useful for most cases, +but any positive number may be used for advanced configurations.
+In many cases it may be simpler to use forUnmatchedRequest() to set a fallback +rule explicitly, rather than manually setting the priority here.
+Call the given callback for any matched requests that are received, +and build a response from the result.
+The callback should return a response object with the fields as +defined by CallbackResponseMessageResult to define the response, +or the string 'close' to immediately close the connection. The callback +can be asynchronous, in which case it should return this value wrapped +in a promise.
+If the callback throws an exception, the server will return a 500 +with the exception message.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Close connections that match this rule immediately, without +any status code or response.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Forward matched requests on to the specified forwardToUrl. The url +specified must not include a path. Otherwise, an error is thrown. +The path portion of the original request url is used instead.
+The url may optionally contain a protocol. If it does, it will override +the protocol (and potentially the port, if unspecified) of the request. +If no protocol is specified, the protocol (and potentially the port) +of the original request URL will be used instead.
+This method takes options to configure how the request is passed +through. See PassThroughHandlerOptions for the full details +of the options available.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Reply to matched requests with a given status code and the current contents +of a given file. The status message and headers can also be optionally +provided here. If no headers are provided, only the standard required +headers are set.
+The file is read near-fresh for each request, and external changes to its +content will be immediately appear in all subsequent requests.
+If one string argument is provided, it's used as the body file path. +If two are provided (even if one is empty), then 1st is the status message, +and the 2nd the body. This matches the argument order of thenReply().
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Optional
headers: HeadersOptional
headers: HeadersReply to matched requests with the given status & JSON and (optionally) +extra headers.
+This method is (approximately) shorthand for: +server.forGet(...).thenReply(status, JSON.stringify(data), { 'Content-Type': 'application/json' })
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Pass matched requests through to their real destination. This works +for proxied requests only, direct requests will be rejected with +an error.
+This method takes options to configure how the request is passed +through. See PassThroughHandlerOptions for the full details +of the options available.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Optional
options: PassThroughHandlerOptionsReply to matched requests with a given status code and (optionally) status message, +body, headers & trailers.
+If one string argument is provided, it's used as the body. If two are +provided (even if one is empty) then the 1st is the status message, and +the 2nd the body. If no headers are provided, only the standard required +headers are set, e.g. Date and Transfer-Encoding.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Reset connections that match this rule immediately, sending a TCP +RST packet directly, without any status code or response, and without +cleanly closing the TCP connection.
+This is only supported in Node.js versions (>=16.17, >=18.3.0, or
+later), where net.Socket
includes the resetAndDestroy
method.
Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Send a failing error JSON-RPC response to a JSON-RPC request. The error data +can be any JSON-serializable value. If a matching request is received that +is not a valid JSON-RPC request, it will be rejected with an HTTP error.
+Send a successful JSON-RPC response to a JSON-RPC request. The response data +can be any JSON-serializable value. If a matching request is received that +is not a valid JSON-RPC request, it will be rejected with an HTTP error.
+Respond immediately with the given status (and optionally, headers), +and then stream the given stream directly as the response body.
+Note that streams can typically only be read once, and as such +this rule will only successfully trigger once. Subsequent requests +will receive a 500 and an explanatory error message. To mock +repeated requests with streams, create multiple streams and mock +them independently.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Optional
headers: HeadersHold open connections that match this rule, but never respond +with anything at all, typically causing a timeout on the client side.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+A mocked endpoint provides methods to see the current state of +a mock rule.
+Get the requests that this endpoint has seen so far.
+This method returns a promise, which resolves with the requests seen
+up until now, once all ongoing requests have terminated. The returned
+lists are immutable, so won't change if more requests arrive in future.
+Call getSeenRequests
again later to get an updated list.
Requests are included here once the response is completed, even if the request +itself failed, the responses failed or exceptions are thrown elsewhere. To +watch for errors or detailed response info, look at the various server.on(event) +methods.
+Reports whether this endpoint is still pending: if it either hasn't seen the +specified number of requests (if one was specified e.g. with .twice()) +or if it hasn't seen at least one request, by default.
+This method returns a promise, which resolves with the result once all +ongoing requests have terminated.
+WebSocketRuleBuilder
+A builder for defining websocket mock rules. Create one using
+.forAnyWebSocket(path)
on a Mockttp instance, then call whatever
+methods you'd like here to define more precise matching behaviour,
+control how the connection is handled, and how many times this
+rule should be applied.
When you're done, call a .thenX()
method to register the configured rule
+with the server. These return a promise for a MockedEndpoint, which can be
+used to verify the details of the requests matched by the rule.
This returns a promise because rule registration can be asynchronous,
+either when using a remote server or testing in the browser. Wait for the
+promise returned by .thenX()
methods to guarantee that the rule has taken
+effect before sending requests to it.
Match only requests sent to the given host, i.e. the full hostname plus +port included in the request.
+This can behave somewhat confusingly when matching against the default +ports for a protocol (i.e. 80/443), or when specifying a hostname here +without specifying the port. In those cases it's usually better to use +forHostname and/or forPort instead to explicit match the content you're +interested in.
+Match only requests when the callback returns true
+Match only requests whose bodies match (contain equivalent +values, ignoring extra values) the given object, when +parsed as JSON. Matching behaviour is the same as Lodash's +_.isMatch method.
+Note that this only tests that the body can be parsed +as JSON - it doesn't require a content-type header.
+Match only requests whose bodies include the given multipart form data.
+This can take any number of form parts to look for. Each part is specified
+with MultipartFieldMatchCondition object containing one or more of
+name
(string), filename
(string) and content
(string or buffer) as
+fields to match against in the form data.
Requests are matched if all conditions match at least one part in the +request's form data.
+Rest
...matchConditions: MultipartFieldMatchCondition[]Mock rule builders should be constructed through the Mockttp instance you're +using, not directly. You shouldn't ever need to call this constructor.
+Set the rule priority. Any matching rule with a higher priority will always
+take precedence over a matching lower-priority rule, unless the higher rule
+has an explicit completion check (like .once()
) that has already been
+completed.
The RulePriority enum defines the standard values useful for most cases, +but any positive number may be used for advanced configurations.
+In many cases it may be simpler to use forUnmatchedRequest() to set a fallback +rule explicitly, rather than manually setting the priority here.
+Close connections that match this rule immediately, without accepting +the socket or sending any other response.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Accept incoming WebSocket connections, and echo every message +received on the WebSocket back to the client.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Forward matched websockets on to the specified forwardToUrl. The url +specified must not include a path or an error will be thrown. +The path portion of the original request url is used instead.
+The url may optionally contain a protocol. If it does, it will override +the protocol (and potentially the port, if unspecified) of the request. +If no protocol is specified, the protocol (and potentially the port) +of the original request URL will be used instead.
+This method takes options to configure how the request is passed +through. See PassThroughWebSocketHandlerOptions for the full +details of the options available.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Accept incoming WebSocket connections, and simply listen to +incoming messages without ever sending anything in return.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Pass matched websockets through to their real destination. This works +for proxied requests only, and direct requests will be rejected with +an error.
+This method takes options to configure how the request is passed +through. See PassThroughWebSocketHandlerOptions for the full +details of the options available.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Rejects connections, sending an HTTP response with the given +status, message and body, to explicitly refuse the WebSocket +handshake.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Optional
statusMessage: stringOptional
headers: HeadersOptional
body: string | BufferReset connections that match this rule immediately, sending a TCP +RST packet directly, without accepting the socket or sending any +other response, and without cleanly closing the TCP connection.
+This is only supported in Node.js versions (>=16.17, >=18.3.0, or
+later), where net.Socket
includes the resetAndDestroy
method.
Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Hold open connections that match this rule, but never respond +with anything at all, typically causing a timeout on the client side.
+Calling this method registers the rule with the server, so it +starts to handle requests.
+This method returns a promise that resolves with a mocked endpoint. +Wait for the promise to confirm that the rule has taken effect +before sending requests to be matched. The mocked endpoint +can be used to assert on the requests matched by this rule.
+Readonly
typeReadonly
typeReadonly
regexReadonly
typeReadonly
regexReadonly
regexReadonly
typeReadonly
regexReadonly
regexReadonly
typeOptional
headers: HeadersOptional
Readonly
beforeOptional
Readonly
beforeReadonly
clientReadonly
extraCACertificatesOptional
Readonly
forwardingReadonly
ignoreOptional
Readonly
lookupOptional
Readonly
proxyReadonly
simulateOptional
Readonly
transformOptional
Readonly
transformReadonly
typeOptional
statusMessage: stringOptional
data: Optional
headers: HeadersOptional
trailers: TrailersOptional
headers: HeadersOptional
code: stringOptional
headers: HeadersOptional
headersReadonly
typeReadonly
resultReadonly
typeOptional
Readonly
beforeOptional
Readonly
beforeReadonly
clientReadonly
extraCACertificatesOptional
Readonly
forwardingReadonly
ignoreOptional
Readonly
lookupOptional
Readonly
proxyReadonly
simulateOptional
Readonly
transformOptional
Readonly
transformReadonly
typeOptional
statusMessage: stringOptional
data: Optional
headers: HeadersOptional
trailers: TrailersOptional
dataOptional
headersOptional
statusOptional
trailersReadonly
typeOptional
headers: HeadersOptional
headersReadonly
typeReadonly
clientReadonly
extraCACertificatesOptional
Readonly
forwardingReadonly
ignoreReadonly
lookupOptional
Readonly
proxyReadonly
typeReadonly
clientReadonly
extraCACertificatesOptional
Readonly
forwardingReadonly
ignoreReadonly
lookupOptional
Readonly
proxyReadonly
typeReadonly
bodyReadonly
headersReadonly
statusReadonly
statusReadonly
typeGenerate a CA certificate for mocking HTTPS.
+Returns a promise, for an object with key and cert properties, +containing the generated private key and certificate in PEM format.
+These can be saved to disk, and their paths passed +as HTTPS options to a Mockttp server.
+Optional
bits?: numberOptional
commonOptional
countryOptional
nameOptional
permitted?: string[]Optional
organizationGet a Mockttp admin server, which can be used with a Mockttp remote client to create +& manage Mockttp instances either from remote machines or from local environments +that lack necessary capabilities, e.g. to use Mockttp from inside a browser.
+This function exists so you can set up these servers programmatically, but for most
+usage you can just run your tests via the mockttp
binary, which will automatically
+start and stop an admin server for you:
mockttp -c <your test command>
+
+
+Get a Mockttp instance on the local machine.
+In most simple environments, you can call this method directly and immediately +get a Mockttp instance and start mocking servers.
+In node, the mocked servers will run in process and require no further setup.
+In browsers this is an alias for getRemote. You'll need to start a Mockttp admin server +outside your tests before calling this, which will create and manage your fake servers +outside the browser.
+Get a Mockttp instance, controlled through a Mockttp admin server.
+This connects to a Mockttp admin server, and uses that to start +and stop mock servers.
+Reset a remote admin server, shutting down all Mockttp servers controlled by that
+admin server. This is equivalent to calling client.stop()
for all remote
+clients of the target server.
This can be useful in some rare cases, where a client might fail to reliably tear down +its own server, e.g. in Cypress testing. In this case, it's useful to reset the +admin server completely remotely without needing access to any previous client +instances, to ensure all servers from previous test runs have been shut down.
+After this is called, behaviour of any previously connected clients is undefined, and
+it's likely that they may throw errors or experience other undefined behaviour. Ensure
+that client.stop()
has been called on all active clients before calling this method.
++Part of HTTP Toolkit: powerful tools for building, testing & debugging HTTP(S)
+
These are the API reference docs for Mockttp. If you're not sure what Mockttp is, it's best to start from the README instead.
+On the other hand, if you're looking for detailed documentation, you're in the right place!
+From here you can explore all the exported types and statically exported functions from the sidebar on the right, you can use the search button (top right) to jump to specific documentation by name, or you're not sure you probably want to start at the Mockttp type and follow the types from there.
+Can't find what you're looking for, missing important info, or generally confused? Please file an issue and help Mockttp's docs get better.
+Optional
errorOptional
hostnameOptional
httpOptional
matchedOptional
remoteOptional
remoteA client error event describes a request (or our best guess at parsing it), +that wasn't correctly completed, and the error response it received, or +'aborted' if the connection was disconnected before we could respond.
+Optional
errorThe raw bytes of the response. If a content encoding was used, this is +the raw encoded data.
+The contents of the response, decoded, and then parsed automatically as +either one of the form encoding types (either URL-encoded or multipart), +determined automatically from the message content-type header.
+This method is convenient and offers a single mechanism to parse both
+formats, but you may want to consider parsing on format explicitly with
+the getUrlEncodedFormData()
or getMultipartFormData()
methods instead.
After parsing & decoding, the result is returned asynchronously as a +Promise for a key-value(s) object.
+The contents of the response, decoded, and then parsed as multi-part +form data. The response is result is returned asynchronously as a +Promise for an array of parts with their names, data and metadata.
+The contents of the response, decoded, parsed as UTF-8 string, and then +parsed as URL-encoded form data. After parsing & decoding, the result is +returned asynchronously as a Promise for a key-value(s) object.
+Optional
hostnameOptional
httpOptional
matchedOptional
remoteOptional
remoteOptional
:authorityOptional
:methodOptional
:pathOptional
:schemeOptional
content-Optional
content-Optional
cookieOptional
hostOptional
user-Optional
countryThe countryName that will be used in the certificate for incoming TLS +connections.
+Optional
keyMinimum key length when generating certificates. Defaults to 2048.
+Optional
localityThe localityName that will be used in the certificate for incoming TLS +connections.
+Optional
organizationThe organizationName that will be used in the certificate for incoming TLS +connections.
+Optional
countryThe countryName that will be used in the certificate for incoming TLS +connections.
+Optional
keyMinimum key length when generating certificates. Defaults to 2048.
+Optional
localityThe localityName that will be used in the certificate for incoming TLS +connections.
+Optional
organizationThe organizationName that will be used in the certificate for incoming TLS +connections.
+A mocked endpoint provides methods to see the current state of +a mock rule.
+Get the requests that this endpoint has seen so far.
+This method returns a promise, which resolves with the requests seen
+up until now, once all ongoing requests have terminated. The returned
+lists are immutable, so won't change if more requests arrive in future.
+Call getSeenRequests
again later to get an updated list.
Requests are included here once the response is completed, even if the request +itself failed, the responses failed or exceptions are thrown elsewhere. To +watch for errors or detailed response info, look at the various server.on(event) +methods.
+Reports whether this endpoint is still pending: if it either hasn't seen the +specified number of requests (if one was specified e.g. with .twice()) +or if it hasn't seen at least one request, by default.
+This method returns a promise, which resolves with the result once all +ongoing requests have terminated.
+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();
+
+
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+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.
+Rest
...ruleData: RequestRuleData[]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.
+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.
+Rest
...ruleData: WebSocketRuleData[]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.
+Rest
...ruleData: RequestRuleData[]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.
+Rest
...ruleData: WebSocketRuleData[]The port the server is running on.
+This will throw an error if read before the server is started.
+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)
+
+
+The root URL of the server.
+This will throw an error if read before the server is started.
+Returns the set of currently registered mock endpoints.
+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.
+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.
+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()
.
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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpMatch 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
+Optional
match: { Optional
method?: stringOptional
params?: anyGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/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.
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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:
+/abc
) will be compared only to the request's path,
+independent of the host & protocol, ignoring query params.localhost:8000/abc
) will be
+compared to the URL independent of the protocol, ignoring query params.http://localhost:8000/abc
) will be compared
+to entire URL, ignoring query params./^http://localhost:8000/abc$/
/^/abc/
Optional
url: string | RegExpGet 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.
Get a builder for a mock rule that will match all websocket connections.
+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.
+Optional
port: number | PortRangeOptional
corsSet CORS options to limit the sites which can send requests to manage this admin server.
+Optional
debugShould the admin server print extra debug information? This enables admin server debugging +only - individual mock session debugging must be enabled separately.
+Optional
ruleSome rule options can't easily be specified in remote clients, since they need to access
+server-side state or Node APIs directly. To handle this, referenceable parameters can
+be provided here, and referenced with a { [MOCKTTP_PARAM_REF]: <value> }
value in place
+of the real parameter in the remote client.
Optional
serverOverride the default parameters for servers started from this admin server. These values will be +used for each setting that is not explicitly specified by the client when creating a mock server.
+Optional
webSet a keep alive frequency in milliseconds for the subscription & stream websockets of each +session, to ensure they remain connected in long-lived connections, especially in browsers which +often close quiet background connections automatically.
+Optional
adminThe full URL to use to connect to a Mockttp admin server when using a +remote (or local but browser) client.
+When using a local server, this option is ignored.
+Optional
clientOptions to include on all client requests, e.g. to add extra +headers for authentication.
+Optional
corsShould the server automatically respond to OPTIONS requests with a permissive +response?
+Defaults to true for remote clients (e.g. in the browser), and false otherwise. +If this is set to false, browser requests will typically fail unless you +stub OPTIONS responses by hand.
+Optional
debugShould the server print extra debug information?
+Optional
http2Should HTTP/2 be enabled? Can be true, false, or 'fallback'. If true, +HTTP/2 is used for all clients supporting it. If false, HTTP/2 is never +used. If 'fallback' HTTP/2 is used only for clients that do not advertise +support for HTTP/1.1, but HTTP/1.1 is used by preference in all other +cases.
+Client HTTP/2 support is only advertised as part of the TLS options. +When no HTTPS configuration is provided, 'fallback' is equivalent to +false.
+Optional
httpsThe HTTPS settings to be used. Optional, only HTTP interception will be +enabled if omitted. This should be set to either a { key, cert } object +containing the private key and certificate in PEM format, or a { keyPath, +certPath } object containing the path to files containing that content.
+Optional
maxThe maximum body size to process, in bytes.
+Bodies larger than this will be dropped, becoming empty, so they won't match +body matchers, won't be available in .seenRequests, and won't be included in +subscribed event data. Body data will still typically be included in passed +through request & response data, in most cases, so this won't affect the +external HTTP clients otherwise.
+Optional
recordRecord the requests & response for all traffic matched by each rule, and make +it available via endpoint.getSeenRequests().
+Defaults to true. It can be useful to set this to false if lots of data will +be sent to/via the server, to avoid storing all traffic in memory unnecessarily, +if getSeenRequests will not be used.
+If this is set to false then getSeenRequests() will always return +an empty array. This only disables the built-in persistence of request data, +so traffic can still be captured live or stored elsewhere using +.on('request') & .on('response').
+Optional
suggestBy default, requests that match no rules will receive an explanation of the +request & existing rules, followed by some suggested example Mockttp code +which could be used to match the rule.
+In some cases where the end client is unaware of Mockttp, these example
+suggestions are just confusing. Set suggestChanges
to false to disable it.
Optional
corsShould the server automatically respond to OPTIONS requests with a permissive +response?
+Defaults to true for remote clients (e.g. in the browser), and false otherwise. +If this is set to false, browser requests will typically fail unless you +stub OPTIONS responses by hand.
+Optional
debugShould the server print extra debug information?
+Optional
http2Should HTTP/2 be enabled? Can be true, false, or 'fallback'. If true, +HTTP/2 is used for all clients supporting it. If false, HTTP/2 is never +used. If 'fallback' HTTP/2 is used only for clients that do not advertise +support for HTTP/1.1, but HTTP/1.1 is used by preference in all other +cases.
+Client HTTP/2 support is only advertised as part of the TLS options. +When no HTTPS configuration is provided, 'fallback' is equivalent to +false.
+Optional
httpsThe HTTPS settings to be used. Optional, only HTTP interception will be +enabled if omitted. This should be set to either a { key, cert } object +containing the private key and certificate in PEM format, or a { keyPath, +certPath } object containing the path to files containing that content.
+Optional
maxThe maximum body size to process, in bytes.
+Bodies larger than this will be dropped, becoming empty, so they won't match +body matchers, won't be available in .seenRequests, and won't be included in +subscribed event data. Body data will still typically be included in passed +through request & response data, in most cases, so this won't affect the +external HTTP clients otherwise.
+Optional
recordRecord the requests & response for all traffic matched by each rule, and make +it available via endpoint.getSeenRequests().
+Defaults to true. It can be useful to set this to false if lots of data will +be sent to/via the server, to avoid storing all traffic in memory unnecessarily, +if getSeenRequests will not be used.
+If this is set to false then getSeenRequests() will always return +an empty array. This only disables the built-in persistence of request data, +so traffic can still be captured live or stored elsewhere using +.on('request') & .on('response').
+Optional
suggestBy default, requests that match no rules will receive an explanation of the +request & existing rules, followed by some suggested example Mockttp code +which could be used to match the rule.
+In some cases where the end client is unaware of Mockttp, these example
+suggestions are just confusing. Set suggestChanges
to false to disable it.
Optional
hostnameOptional
httpOptional
matchedOptional
rawOptional
remoteOptional
remoteReturns a shallow copy of the current outgoing headers. Since a shallow +copy is used, array values may be mutated without additional calls to +various header-related HTTP module methods. The keys of the returned +object are the header names and the values are the respective header +values. All header names are lowercase.
+The object returned by the outgoingMessage.getHeaders()
method does
+not prototypically inherit from the JavaScript Object
. This means that
+typical Object
methods such as obj.toString()
, obj.hasOwnProperty()
,
+and others are not defined and will not work.
outgoingMessage.setHeader('Foo', 'bar');
outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headers = outgoingMessage.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
+
+
+This defines the upstream connection parameters. These passthrough parameters +are shared between both WebSocket & Request passthrough rules.
+Optional
additionalAn array of additional certificates, which should be trusted as certificate +authorities for upstream hosts, in addition to Node.js's built-in certificate +authorities.
+Each certificate should be an object with either a cert
key and a string
+or buffer value containing the PEM certificate, or a certPath
key and a
+string value containing the local path to the PEM certificate.
Optional
clientA mapping of hosts to client certificates to use, in the form of
+{ key, cert }
objects (none, by default)
Optional
forwardingThe forwarding configuration for the passthrough rule.
+This generally shouldn't be used explicitly unless you're
+building rule data by hand. Instead, call thenPassThrough
+to send data directly or thenForwardTo
with options to
+configure traffic forwarding.
Optional
ignoreA list of hostnames for which server certificate and TLS version errors +should be ignored (none, by default).
+If set to 'true', HTTPS errors will be ignored for all hosts. WARNING:
+Use this at your own risk. Setting this to true
can open your
+application to MITM attacks and should never be used over any network
+that is not completed trusted end-to-end.
Optional
lookupCustom DNS options, to allow configuration of the resolver used +when forwarding requests upstream. Passing any option switches +from using node's default dns.lookup function to using the +cacheable-lookup module, which will cache responses.
+Optional
proxyUpstream proxy configuration: pass through requests via this proxy.
+If this is undefined, no proxy will be used. To configure a proxy +provide either:
+When using a remote client, this parameter or individual array +values may be passed by reference, using the name of a rule +parameter configured in the admin server.
+Optional
trustDeprecated alias for additionalTrustedCAs
Optional
adminThe full URL to use to connect to a Mockttp admin server when using a +remote (or local but browser) client.
+When using a local server, this option is ignored.
+Optional
adminIf the admin stream disconnects, how many times should we try to +reconnect? Increasing this can be useful in unstable environments, such +as desktop app use case, while fewer retries will provide faster shutdown +in environments where you may be killing processes intentionally.
+Optional
debugShould the client print extra debug information?
+Optional
requestOptions to include on all client requests.
+Optional
corsSet CORS options to limit the sites which can send requests to manage this admin server.
+Optional
debugShould the admin server print extra debug information? This enables admin server debugging +only - individual mock session debugging must be enabled separately.
+Optional
pluginOverride the default parameters for sessions started from this admin server. These values will be +used for each setting that is not explicitly specified by the client when creating a mock session.
+Optional
ruleSome rule options can't easily be specified in remote clients, since they need to access
+server-side state or Node APIs directly. To handle this, referenceable parameters can
+be provided here, and referenced with a { [MOCKTTP_PARAM_REF]: <value> }
value in place
+of the real parameter in the remote client.
Optional
webSet a keep alive frequency in milliseconds for the subscription & stream websockets of each +session, to ensure they remain connected in long-lived connections, especially in browsers which +often close quiet background connections automatically.
+A ProxySetting is a specific proxy setting to use, which is passed to a proxy agent +who will manage creating a socket for the request (directly, or tunnelled, or whatever).
+Optional
additionalExtra CAs to trust for HTTPS connections to the proxy. Ignored if the connection +to the proxy is not HTTPS.
+This appends to the list of trusted CAs, and is mutually exclusive with the
+trustedCAs
option, which completely overrides the list of CAs.
Optional
noA list of no-proxy values, matching hosts' traffic should not be proxied.
+This is a common proxy feature, but unfortunately isn't standardized. See +https://about.gitlab.com/blog/2021/01/27/we-need-to-talk-no-proxy/ for some +background. This implementation is intended to match Curl's behaviour, and +any differences are a bug.
+The currently supported formats are:
+Some other formats (e.g. leading dots or *.) will work, but the leading +characters are ignored. More formats may be added in future, e.g. CIDR ranges. +To maximize compatibility with values used elsewhere, unrecognized formats +will generally be ignored, but may match in unexpected ways.
+The URL for the proxy to forward traffic through.
+This can be any URL supported by https://www.npmjs.com/package/proxy-agent. +For example: http://..., socks5://..., pac+http://...
+Optional
trustedCAsCAs to trust for HTTPS connections to the proxy. Ignored if the connection to +the proxy is not HTTPS. If not specified, this will default to the Node +defaults, or you can override them here completely.
+This sets the complete list of trusted CAs, and is mutually exclusive with the
+additionalTrustedCAs
option, which adds additional CAs (but also trusts the
+Node default CAs too).
This should be specified as either a { cert: string | Buffer } object or a +{ certPath: string } object (to read the cert from disk). The previous +simple string format is supported but deprecated.
+Optional
hostnameOptional
httpOptional
matchedOptional
remoteOptional
remoteOptional
abortedOptional
bodyOptional
headersOptional
responseOptional
wsOptional
wsWhen the socket initially connected, equivalent to startTime.
+High-precision floating-point monotonically increasing timestamps. +Comparable and precise, but not related to specific current time.
+Optional
disconnectWhen the connection was closed, if it has been closed.
+When the TLS connection failed. This may be due to a failed handshake
+(in which case handshakeTimestamp
will be undefined) or due to a
+subsequent error which means the TLS connection was not usable (like
+an immediate closure due to an async certificate rejection).
Optional
handshakeWhen Mockttp's handshake for this connection was completed (if there +was one). This is not set for passed through connections.
+When the socket initially connected, in MS since the unix +epoch.
+Optional
tunnelWhen the outer tunnel (e.g. a preceeding CONNECT request) was created, +if there was one.
+When the socket initially connected, equivalent to startTime.
+High-precision floating-point monotonically increasing timestamps. +Comparable and precise, but not related to specific current time.
+Optional
disconnectWhen the connection was closed, if it has been closed.
+Optional
handshakeWhen Mockttp's handshake for this connection was completed (if there +was one). This is not set for passed through connections.
+When the socket initially connected, in MS since the unix +epoch.
+Optional
tunnelWhen the outer tunnel (e.g. a preceeding CONNECT request) was created, +if there was one.
+The close code of the shutdown. This is the close code that was received +from the remote client (either initiated remotely, or echoing our own sent +close frame).
+This may be undefined only if a close frame was received but did not contain +any close code. If no close frame was received before the connection was +lost (i.e. the connection was not cleanly closed) this event will not +fire at all, and an 'abort' event will fire instead.
+The close reason of the shutdown.
+The id of this websocket stream. This will match the id of the request, +the initial connection response, and any other WebSocket events for the +same connection stream.
+The contents of the message as a raw buffer. This is already decompressed, +if the WebSocket uses compression.
+Whether the message was sent by Mockttp, or received from a Mockttp client.
+A high-precision floating-point monotonically increasing timestamp. +Comparable and precise, but not related to specific current time.
+To link this to the current time, compare it to timingEvents.startTime
.
Whether this is a string message or a raw binary data message.
+The id of this websocket stream. This will match the id of the request, +the initial connection response, and any other WebSocket events for the +same connection stream.
+Can be returned from callbacks to override parts of a request.
+All fields are optional, and omitted values will default to the original +request value.
+Optional
bodyA string or buffer, which replaces the request body if set. This will +be automatically content-encoded to match the Content-Encoding defined +in your request headers.
+If this is set, the Content-Length header will be automatically updated
+accordingly to match, unless you also provide a headers
value that
+includes a Content-Length header, in which case that will take used
+as-is.
You should only return one body field: either body
, rawBody
or
+json
.
Optional
headersThe replacement HTTP headers, as an object of string keys and either +single string or array of string values.
+Optional
jsonA JSON value, which will be stringified and send as a JSON-encoded +request body. This will be automatically content-encoded to match +the Content-Encoding defined in your request headers.
+If this is set, the Content-Length header will be automatically updated
+accordingly to match, unless you also provide a headers
value that
+includes a Content-Length header, in which case that will take used
+as-is.
You should only return one body field: either body
, rawBody
or
+json
.
Optional
methodA replacement HTTP method, capitalized.
+Optional
rawA buffer, which replaces the request body if set, which is sent exactly +as is, and is not automatically encoded.
+If this is set, the Content-Length header will be automatically updated
+accordingly to match, unless you also provide a headers
value that
+includes a Content-Length header, in which case that will take used
+as-is.
You should only return one body field: either body
, rawBody
or
+json
.
Optional
responseA response: either a response object defining the fields of a response +or the string 'close' to immediately close the connection.
+See CallbackResponseMessageResult for the possible fields that can +be set to define the response.
+If set, the request will not be forwarded at all, and this will be used +as the response to immediately return to the client (or for 'close', this +will immediately close the connection to the client).
+Optional
urlThe full URL to send the request to. If set, this will redirect
+the request and automatically update the Host header accordingly,
+unless you also provide a headers
value that includes a Host
+header, in which case that will take used as-is.
Can be returned from callbacks to define parts of a response, or +override parts when given an existing repsonse.
+All fields are optional, and omitted values will default to the original +response value or a default value.
+Optional
bodyA string or buffer, which replaces the response body if set. This will +be automatically encoded to match the Content-Encoding defined in your +response headers.
+If this is set, the Content-Length header will be automatically updated
+accordingly to match, unless you also provide a headers
value that
+includes a Content-Length header, in which case that will take used
+as-is.
Defaults to empty.
+You should only return one body field: either body
, rawBody
or
+json
.
Optional
headersThe replacement HTTP headers, as an object of string keys and either +single string or array of string values.
+Defaults to a minimum set of standard required headers if not set.
+Optional
jsonA JSON value, which will be stringified and send as a JSON-encoded +request body. This will be automatically content-encoded to match the +Content-Encoding defined in your response headers.
+If this is set, the Content-Length header will be automatically updated
+accordingly to match, unless you also provide a headers
value that
+includes a Content-Length header, in which case that will take used
+as-is.
You should only return one body field: either body
, rawBody
or
+json
.
Optional
rawA buffer, which replaces the response body if set, which is sent exactly +as is, and is not automatically encoded.
+If this is set, the Content-Length header will be automatically updated
+accordingly to match, unless you also provide a headers
value that
+includes a Content-Length header, in which case that will take used
+as-is.
You should only return one body field: either body
, rawBody
or
+json
.
Optional
statusSupported only for backward compatibility.
+Optional
statusThe response status code as a number.
+Defaults to 200 if not set.
+Optional
statusThe response status message, as a string. This is ignored for +HTTP/2 responses.
+Defaults to the default status message for the status code if not set.
+Optional
trailersThe replacement HTTP trailers, as an object of string keys and either +single string or array of string values. Note that there are not all +header fields are valid as trailers, and there are other requirements +such as chunked encoding that must be met for trailers to be sent +successfully.
+This defines the upstream connection parameters. These passthrough parameters +are shared between both WebSocket & Request passthrough rules.
+Optional
additionalAn array of additional certificates, which should be trusted as certificate +authorities for upstream hosts, in addition to Node.js's built-in certificate +authorities.
+Each certificate should be an object with either a cert
key and a string
+or buffer value containing the PEM certificate, or a certPath
key and a
+string value containing the local path to the PEM certificate.
Optional
beforeA callback that will be passed the full request before it is passed through, +and which returns an object that defines how the the request content should +be transformed before it's passed to the upstream server.
+The callback can return an object to define how the request should be changed. +All fields on the object are optional, and returning undefined is equivalent +to returning an empty object (transforming nothing).
+See CallbackRequestResult for the possible fields that can be set.
+Optional
beforeA callback that will be passed the full response before it is passed through, +and which returns a value that defines how the the response content should +be transformed before it's returned to the client.
+The callback can either return an object to define how the response should be +changed, or the string 'close' to immediately close the underlying connection.
+All fields on the object are optional, and returning undefined is equivalent +to returning an empty object (transforming nothing).
+See CallbackResponseMessageResult for the possible fields that can be set.
+Optional
clientA mapping of hosts to client certificates to use, in the form of
+{ key, cert }
objects (none, by default)
Optional
forwardingThe forwarding configuration for the passthrough rule.
+This generally shouldn't be used explicitly unless you're
+building rule data by hand. Instead, call thenPassThrough
+to send data directly or thenForwardTo
with options to
+configure traffic forwarding.
Optional
ignoreA list of hostnames for which server certificate and TLS version errors +should be ignored (none, by default).
+If set to 'true', HTTPS errors will be ignored for all hosts. WARNING:
+Use this at your own risk. Setting this to true
can open your
+application to MITM attacks and should never be used over any network
+that is not completed trusted end-to-end.
Optional
lookupCustom DNS options, to allow configuration of the resolver used +when forwarding requests upstream. Passing any option switches +from using node's default dns.lookup function to using the +cacheable-lookup module, which will cache responses.
+Optional
proxyUpstream proxy configuration: pass through requests via this proxy.
+If this is undefined, no proxy will be used. To configure a proxy +provide either:
+When using a remote client, this parameter or individual array +values may be passed by reference, using the name of a rule +parameter configured in the admin server.
+Optional
simulateWhether to simulate connection errors back to the client.
+By default (in most cases - see below) when an upstream request fails +outright a 502 "Bad Gateway" response is sent to the downstream client, +explicitly indicating the failure and containing the error that caused +the issue in the response body.
+Only in the case of upstream connection reset errors is a connection reset +normally sent back downstream to existing clients (this behaviour exists +for backward compatibility, and will change to match other error behaviour +in a future version).
+When this option is set to true
, low-level connection failures will
+always trigger a downstream connection close/reset, rather than a 502
+response.
This includes DNS failures, TLS connection errors, TCP connection resets, +etc (but not HTTP non-200 responses, which are still proxied as normal). +This is less convenient for debugging in a testing environment or when +using a proxy intentionally, but can be more accurate when trying to +transparently proxy network traffic, errors and all.
+Optional
transformA set of data to automatically transform a request. This includes properties +to support many transformation common use cases.
+For advanced cases, a custom callback using beforeRequest can be used instead. +Using this field however where possible is typically simpler, more declarative, +and can be more performant. The two options are mutually exclusive: you cannot +use both transformRequest and a beforeRequest callback.
+Only one transformation for each target (method, headers & body) can be +specified. If more than one is specified then an error will be thrown when the +rule is registered.
+Optional
transformA set of data to automatically transform a response. This includes properties +to support many transformation common use cases.
+For advanced cases, a custom callback using beforeResponse can be used instead. +Using this field however where possible is typically simpler, more declarative, +and can be more performant. The two options are mutually exclusive: you cannot +use both transformResponse and a beforeResponse callback.
+Only one transformation for each target (status, headers & body) can be +specified. If more than one is specified then an error will be thrown when the +rule is registered.
+Optional
trustDeprecated alias for additionalTrustedCAs
Optional
errorHow long to cache a DNS ENODATA or ENOTFOUND response. Defaults +to 0.15.
+Optional
maxThe maximum time to cache a DNS response. Up to this limit, +responses will be cached according to their own TTL. Defaults +to Infinity.
+Optional
serversThe primary servers to use. DNS queries will be resolved against +these servers first. If no data is available, queries will fall +back to dns.lookup, and use the OS's default DNS servers.
+This defaults to dns.getServers().
+Optional
matchPerform a series of string match & replace operations on the request body.
+This parameter should be an array of pairs, which will be applied to the body
+decoded as a string like body.replace(p1, p2)
, applied in the order provided.
+The first parameter can be either a string or RegExp to match, and the second
+must be a string to insert. The normal str.replace
$ placeholders can be
+used in the second argument, so that e.g. $1 will insert the 1st matched group.
Optional
patchA series of operations to apply to the request body in JSON Patch format (RFC +6902).
+Any requests which are received with an invalid JSON body that match this rule +will fail.
+Optional
replaceA string or buffer that replaces the request body entirely.
+If this is specified, the upstream request will not wait for the original request +body, so this may make responses faster than they would be otherwise given large +request bodies or slow/streaming clients.
+Optional
replaceThe path to a file, which will be used to replace the request body entirely. The +file will be re-read for each request, so the body will always reflect the latest +file contents.
+If this is specified, the upstream request will not wait for the original request +body, so this may make responses faster than they would be otherwise given large +request bodies or slow/streaming clients.
+Optional
replaceA headers object which will completely replace the real request headers.
+Optional
replaceA replacement HTTP method. Case insensitive.
+Optional
updateA headers object which will be merged with the real request headers to add or +replace values. Headers with undefined values will be removed.
+Optional
updateA JSON object which will be merged with the real request body. Undefined values +will be removed, and other values will be merged directly with the target value +recursively.
+Any requests which are received with an invalid JSON body that match this rule +will fail.
+Optional
matchPerform a series of string match & replace operations on the response body.
+This parameter should be an array of pairs, which will be applied to the body
+decoded as a string like body.replace(p1, p2)
, applied in the order provided.
+The first parameter can be either a string or RegExp to match, and the second
+must be a string to insert. The normal str.replace
$ placeholders can be
+used in the second argument, so that e.g. $1 will insert the 1st matched group.
Optional
patchA series of operations to apply to the response body in JSON Patch format (RFC +6902).
+Any responses which are received with an invalid JSON body that match this rule +will fail.
+Optional
replaceA string or buffer that replaces the response body entirely.
+If this is specified, the downstream response will not wait for the original response +body, so this may make responses arrive faster than they would be otherwise given large +response bodies or slow/streaming servers.
+Optional
replaceThe path to a file, which will be used to replace the response body entirely. The +file will be re-read for each response, so the body will always reflect the latest +file contents.
+If this is specified, the downstream response will not wait for the original response +body, so this may make responses arrive faster than they would be otherwise given large +response bodies or slow/streaming servers.
+Optional
replaceA headers object which will completely replace the real response headers.
+Optional
replaceA replacement response status code.
+Optional
updateA headers object which will be merged with the real response headers to add or +replace values. Headers with undefined values will be removed.
+Optional
updateA JSON object which will be merged with the real response body. Undefined values +will be removed, and other values will be merged directly with the target value +recursively.
+Any responses which are received with an invalid JSON body that match this rule +will fail.
+This API is not yet stable, and is intended for internal use only. It may change in future +in minor versions without warning.
+These plugin components can be applied to the PluggableAdmin API to create a remotely +controlable mock management server that can mock HTTP in addition to protocols from +other plugins.
+This API is not yet stable, and is intended for internal use only. It may change in future +in minor versions without warning.
+These generic pluggable admin components allow composing an admin server and client that +are capable of managing arbitrary mock protocols, including Mockttp but also others depending +on the admin plugins used. To use Mockttp, combine this with the MockttpPluggableAdmin API.
+Optional
defaultThe domain name that will be used in the certificate for incoming TLS +connections which don't use SNI to request a specific domain.
+Optional
tlsA limited list of the only hostnames whose TLS should be intercepted.
+This is the opposite of tlsPassthrough
. When set, only connections
+to these hostnames will be intercepted, and all other TLS connections will
+be passed through without interception.
This option is mutually exclusive with tlsPassthrough
and setting both
+options will throw an error.
Each element in this list must be an object with a 'hostname' field for the
+hostname that should be matched. Wildcards are supported (following the
+URLPattern specification),
+eg. {hostname: '*.example.com'}
.
In future more options may be supported +here for additional configuration of this behaviour.
+Optional
tlsA list of hostnames where TLS interception should always be skipped.
+When a TLS connection is started that references a matching hostname in its +server name indication (SNI) extension, or which uses a matching hostname +in a preceeding CONNECT request to create a tunnel, the connection will be +sent raw to the upstream hostname, without handling TLS within Mockttp (i.e. +with no TLS interception performed).
+This option is mutually exclusive with tlsInterceptOnly
and setting both
+options will throw an error.
Each element in this list must be an object with a 'hostname' field for the
+hostname that should be matched. Wildcards are supported (following the
+URLPattern specification),
+eg. {hostname: '*.example.com'}
.
In future more options may be supported +here for additional configuration of this behaviour.
+A ProxyConfig is externally provided config that specifies a ProxySettingSource. +It might be a ProxySettingSource itself, or it might include references to rule +parameters, which must be dereferenced to make it usable as a ProxySettingSource.
+A ProxySettingSource is a way to calculate the ProxySetting for a given request. It +may be a fixed ProxySetting value, or a callback to get ProxySetting values, or an +array of sources, which should be iterated to get the first usable value
+A reference to a rule parameter defined in the ruleParameters
admin server
+option of the corresponding admin server.
Rule parameter references are only valid with a remote client. They can be useful in +cases where the admin server has access to local state or APIs that are not +accessible from the remote client, but which would be useful in rule definitions. This +is only supported for some specific parameters where documented explicitly in that rule +parameter.
+Const
Const
Const
Const
Const
Const
Const
Subscribe to hear when each mock ession is started. The listener is provided the +session plugin data, which can be used to log session startup, add side-effects that +run elsewhere at startup, or preconfigure every started plugin in addition ways.
+This is run synchronously when a session is created, after it has fully started +but before its been returned to remote clients.
+