undici icon indicating copy to clipboard operation
undici copied to clipboard

Allow asynchronous mocking replies

Open LuudJanssen opened this issue 2 years ago • 9 comments

This would solve...

When trying to create a Undici adapter for Polly.JS I tried to use the mocking capabilities from Undici to record network requests and replay them later using stored HAR files. However, the MockInterceptor.reply method doesn't support asynchronous callbacks. So receiving the request, loading a file from the filesystem (asynchronously) (or passing through the request) and resolving with a promise doesn't work.

Sidenote: nock supports asynchronous callbacks: https://github.com/nock/nock#specifying-replies

The implementation should look like...

The MockInterceptor.reply method could accept asynchronous callbacks:

mockPool
  .intercept({
    path: () => true
  })
  .reply(async (options) => {
    const response = await fetchFromFileSystem(options)
    return mapping(response)
  })

I have also considered...

Creating my own version of MockAgent that supports async replies, but that just seemed too much work for a possibly temporary problem.

Additional context

Feature request for Undici adapter for Polly.JS Feature request for Undici support for Nock

LuudJanssen avatar Apr 19 '22 14:04 LuudJanssen

This would be an amazing feature to add? Would you like to send a Pull Request to address this issue? Remember to add unit tests.

mcollina avatar Apr 19 '22 21:04 mcollina

Worked on this over the weekend and have a WIP branch. I'm supposed to leave for vacation tomorrow, so I'll try to at least get a draft PR up today 😅.

Our team is heavily invested in Polly.JS and definitely interested in pursuing a custom Undici adapter.

austinkelleher avatar Apr 25 '22 13:04 austinkelleher

Here is a WIP branch: https://github.com/austinkelleher/undici/commit/5e331e8c036cc37ed659aa8ec850a48ae0f42040

Here is the remaining work:

  • Consider additional edge error cases
  • Add more tests
  • Update TypeScript typings
  • Add documentation

I'm leaving early tomorrow morning for about a week. I'll pick this back up when I get back unless someone else does first! 😅

austinkelleher avatar Apr 25 '22 21:04 austinkelleher

@austinkelleher Could you use any help with this?

kibertoad avatar May 28 '22 12:05 kibertoad

think it should rather be something like fetch event and using respondWith

jimmywarting avatar Jun 11 '22 17:06 jimmywarting