Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Vivi-Ornitier opened this issue May 21, 2022 · 2 comments
Open

Comments

@Vivi-Ornitier
Copy link

Vivi-Ornitier commented May 21, 2022

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?

@pimterry
Copy link
Member

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.

@Vivi-Ornitier
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants