mockttp icon indicating copy to clipboard operation
mockttp copied to clipboard

Question: How to delay the response and how to filter the request?

Open Vivi-Ornitier opened this issue 3 years ago • 2 comments

I want to know how to delay the response and how to filter the request.

Example: mock-http-server

const ServerMock = require("mock-http-server");

var server = new ServerMock({ host: "localhost", port: 9000 });

server.on({
  method: 'GET',
  path: '/resource',
  filter: function (req) {  // <= add filter.
    return _.isEqual(req.body, {
      name: 'someName',
      someOtherValue: 1234
    })
  },
  reply: {
    status:  200,
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ hello: "world" })
  },
  delay: 1000  // <= add delay times.
});

How do I use filter and delay with Mockttp?

Vivi-Ornitier avatar May 21 '22 21:05 Vivi-Ornitier

When defining a rule, you include the conditions for how the rule will match. This is the equivalent of filter. Like so:

mockServer
  .forGet('/resource') // Match GET + path
  .withJsonBody({ name: 'someName', someOtherValue: 1234 }) // Match JSON body
  // ...

There's many more matchers available, see the docs here for a list: https://httptoolkit.github.io/mockttp/classes/RequestRuleBuilder.html. You can also use .matching((req) => /*...*/) to use completely custom matching logic in a callback.

There is no built in support for delays, but it's easy to do yourself with a callback. You can do that like so:

mockServer
  .forGet('/resource') // Match GET + path
  // ... any other matching you want
  .thenCallback(async (req) => {
    // Await a 1000ms promise delay:
    await new Promise((resolve) => setTimeout(resolve, 1000));
    // Then return the response value:
    return {
      status: 200,
      json: { hello: "world" }
    };
  });

I'm open to adding built-in support for delays too, it's definitely an interesting idea, but it needs a little design work to integrate it neatly into the current model. I'll keep an eye on it and see if I can find a good solution there soon.

pimterry avatar May 23 '22 12:05 pimterry

@pimterry Thank you for your reply. I would be grateful if you could support the delay built-in!

Vivi-Ornitier avatar May 24 '22 11:05 Vivi-Ornitier