Class RequestRuleBuilder

RequestRuleBuilder

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.

Hierarchy

  • BaseRuleBuilder
    • RequestRuleBuilder

Completion

  • Run this rule forever, for all matching requests

    Returns this

  • Run this rule only once, for the first matching request

    Returns this

  • Run this rule three times, for the first three matching requests

    Returns this

  • Run this rule the given number of times, for the first matching requests

    Parameters

    • n: number

    Returns this

  • Run this rule twice, for the first two matching requests

    Returns this

Matching

  • 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.

    Parameters

    • host: string

    Returns this

  • Match only requests sent to the given hostname, ignoring the port.

    Parameters

    • hostname: string

    Returns this

  • Match only requests sent to the given port.

    Parameters

    • port: number

    Returns this

  • Match only requests whose bodies either exactly match the given string (if a string is passed) or whose bodies match a regular expression (if a regex is passed).

    Parameters

    • content: string | RegExp

    Returns this

  • Match only requests whose bodies include the given string.

    Parameters

    • content: string

    Returns this

  • Match only requests that include the given cookies

    Parameters

    • cookie: {
          [key: string]: string;
      }
      • [key: string]: string

    Returns this

  • Match only requests that include the exact query string provided. The query string must start with a ? or be entirely empty.

    Parameters

    • query: string

    Returns this

  • Match only requests whose bodies include the given URL-encoded form data.

    Parameters

    • formData: {
          [key: string]: string;
      }
      • [key: string]: string

    Returns this

  • Match only requests that include the given headers.

    Parameters

    • headers: {
          [key: string]: string;
      }
      • [key: string]: string

    Returns this

  • Match only requests whose bodies exactly match the given object, when parsed as JSON.

    Note that this only tests that the body can be parsed as JSON - it doesn't require a content-type header.

    Parameters

    • json: {}

      Returns this

    • 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.

      Parameters

      • json: {}

        Returns this

      • 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.

        Parameters

        Returns this

      • Match only requests sent with the given protocol.

        Parameters

        • protocol:
              | "http"
              | "https"
              | "ws"
              | "wss"

        Returns this

      • Match only requests that include the given query parameters.

        Parameters

        • query: {
              [key: string]: string | number | (string | number)[];
          }
          • [key: string]: string | number | (string | number)[]

        Returns this

      • Match only requests whose absolute url matches the given RegExp.

        Parameters

        • pattern: RegExp

        Returns this

      Other

      • 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.

        Parameters

        • priority: number

        Returns this

      Responses

      • 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.

        Returns Promise<MockedEndpoint>

      • 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.

        Returns Promise<MockedEndpoint>

      • 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.

        Parameters

        Returns Promise<MockedEndpoint>

      • 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.

        Parameters

        • status: number
        • filePath: string
        • Optionalheaders: Headers

        Returns Promise<MockedEndpoint>

      • Parameters

        • status: number
        • statusMessage: string
        • filePath: string
        • Optionalheaders: Headers

        Returns Promise<MockedEndpoint>

      • Reply 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.

        Parameters

        • status: number
        • data: object
        • headers: Headers = {}

        Returns Promise<MockedEndpoint>

      • 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.

        Parameters

        Returns Promise<MockedEndpoint>

      • Reply 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.

        Parameters

        • status: number
        • Optionaldata: string | Buffer
        • Optionalheaders: Headers
        • Optionaltrailers: Trailers

        Returns Promise<MockedEndpoint>

      • Parameters

        • status: number
        • statusMessage: string
        • data: string | Buffer
        • Optionalheaders: Headers
        • Optionaltrailers: Trailers

        Returns Promise<MockedEndpoint>

      • 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.

        Returns Promise<MockedEndpoint>

      • 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.

        Parameters

        • error: any

        Returns Promise<MockedEndpoint>

      • 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.

        Parameters

        • result: any

        Returns Promise<MockedEndpoint>

      • 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.

        Parameters

        • status: number
        • stream: Readable
        • Optionalheaders: Headers

        Returns Promise<MockedEndpoint>

      • 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.

        Returns Promise<MockedEndpoint>