axios-mock-adapter icon indicating copy to clipboard operation
axios-mock-adapter copied to clipboard

Is it possible to add a delay for a specific response?

Open freearhey opened this issue 5 years ago • 5 comments

I mean something like this:

mock.onPost('/any').reply(201, null, { delay: 2000 })

freearhey avatar Dec 14 '19 17:12 freearhey

Since you can reply with a promise, you can use that in combination with setTimeout to have per-request delays:

mock.onGet('/any').reply(function(config) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
        resolve([201, null]);
    }, 2000);
  });
});

If it's something you need to do often, you could write a helper function for it:

const withDelay = (delay, response) => config => {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
        resolve(response);
    }, delay);
  });
});

// And then use it:
mock.onGet('/any').reply(withDelay(2000, [201, null]));

ctimmerm avatar Jan 21 '20 18:01 ctimmerm

@ctimmerm Thanks for the tip! But don't you think it would be better to add this option to the adapter itself?

freearhey avatar Jan 21 '20 23:01 freearhey

It would definitely be nice if we could do something like this:

mock.onGet('/any').delay(1000).reply((config) => {
  return [200];
});

So we don't have to wrap the entire response function with a Promise...

iomariani avatar Aug 28 '20 03:08 iomariani

@ctimmerm An attempt for a helper function for the delay: https://github.com/ctimmerm/axios-mock-adapter/pull/312 Thoughts?

prashanth-92 avatar Sep 06 '21 18:09 prashanth-92

I opened a PR to add types to replyWithDelay

#383

seriouslag avatar Apr 11 '24 18:04 seriouslag