Skip to content

Record and play back requests #4114

@GeoffreyBooth

Description

@GeoffreyBooth

This would solve...

For tests, it's useful to be able to mock the responses to outbound network requests so that tests are not reliant on external resources. This is already possible via MockAgent, but all the examples at https://github.com/nodejs/undici/blob/main/docs/docs/api/MockAgent.md involve writing code to explicitly define each desired mock response. For an app that makes many outbound network requests, it becomes tedious if not impractical to define every response by hand. I would like to somehow record the outbound network requests and their responses, so that later I can attach them to MockAgent to be played back as mocks.

The implementation should look like...

I think this should be achievable using existing APIs, though it isn’t obvious how to do so. I found an implementation by @aduh95 in this comment from several years ago, and a version for fetch is in Corepack. At minimum I think there should be an example in the Undici docs of how to record requests and then use those recordings with MockAgent, assuming this is all possible using existing APIs; and if the example has excessive boilerplate, perhaps a new API such as RecordingAgent could be considered.

I have also considered...

The tool nock has APIs for recording mocks, and the latest version of nock supports Node global fetch, but as far as I can tell nock doesn’t support Undici request. I would like to use request for its increased performance, and because I am using RetryAgent and cacheable-lookup with request.

Additional context

I’ve been searching online for examples of intercepting requests in Undici and besides the mentioned snippets above, the article https://blog.platformatic.dev/http-fundamentals-understanding-undici-and-its-working-mechanism has some interesting examples.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions