jameslnewell / xhr-mock

Utility for mocking XMLHttpRequest.
196 stars 48 forks source link

Possible to add a delay? #61

Closed idolizesc closed 6 years ago

idolizesc commented 6 years ago

I'd like to add a delay to every response (I'm doing some manual testing in the browser and want to simulate how a real server may feel). Is this possible to do? I don't see anything documented.

Thanks!

idolizesc commented 6 years ago

FYI I figured out a way, but it's a bit hacky. Would be nice to have proper support built in :)

mock.get('/url', (_req, _resp) =>
      new Promise((resolve) =>
        delay(DELAY_MS).then(() => {
          const mockResp = new MockResponse();
          mockResp.body(JSON.stringify(mockBody));
          mockResp.status(mockStatus);
          return resolve(mockResp);
        }),
      ),
);
jameslnewell commented 6 years ago

You could use async/await to simplify your handler:

import delay from 'delay';

mock.get('/url', async (req, res) => {
  await delay(DELAY_MS);
  return res
    .body(JSON.stringify(mockBody))
    .status(mockStatus)
  ;
});

What's hacky about that? How would you suggest supporting it built in?

idolizesc commented 6 years ago

Oh, interesting. I didn't realize you could just set the data on the existing res -- in that case it's not very hacky.

Maybe just adding some documentation about how Promises are supported and how you could use them for something like this would be cool 👍

jameslnewell commented 6 years ago

Is mockBody or mockStatus undefined? because all the methods on req/res have two signatures and .status(undefined) means you're returning the status, not the res which will be null and won't have a status property on it.

jameslnewell commented 6 years ago

Care to open a PR for adding a delayed example to the how-to section?

idolizesc commented 6 years ago

Sorry, I actually fixed the other issue (hence deleting my comment). It was because the mockBody was undefined, so it wasn't doing the setter routine, but rather the getter!

idolizesc commented 6 years ago

Sure, I can make a PR for that.