Skip to content

feat(mock): support asynchronous reply options callbacks#5534

Merged
mcollina merged 1 commit into
nodejs:mainfrom
Develop-KIM:feat/async-reply-options-callback
Jul 9, 2026
Merged

feat(mock): support asynchronous reply options callbacks#5534
mcollina merged 1 commit into
nodejs:mainfrom
Develop-KIM:feat/async-reply-options-callback

Conversation

@Develop-KIM

Copy link
Copy Markdown
Contributor

This relates to...

Fixes #1348 (see my comment there clarifying the scope vs #1757/#1758)

Rationale

#1758 made the data argument awaitable (reply(200, async (opts) => body)), but the ask in #1348 — an async reply options callback — still fails on main:

mockPool.intercept({ path: '/fixture' }).reply(async (opts) => ({
  statusCode: 200,
  data: await readFile('./fixture.json')
}))
// InvalidArgumentError: statusCode must be defined

wrappedDefaultsCallback assumes the callback returns a plain object: a Promise passes the typeof === 'object' check, contributes nothing when spread into { data: '', responseOptions: {}, ...promise }, and validation throws. This is what Polly.JS/nock-style record-and-replay adapters need (loading recorded responses from disk asynchronously).

Changes

Extends the existing isPromise pattern from #1758:

  • lib/mock/mock-interceptor.js: wrappedDefaultsCallback detects a promise result and resolves the dispatch data (format check + validation + createMockScopeDispatchData) once it settles.
  • lib/mock/mock-utils.js: mockDispatch detects a promise from the dispatch-data callback and defers the reply (extracted into dispatchMockReply) until it resolves. A rejection can no longer throw synchronously from dispatch, so it is surfaced via handler.onResponseError — the same route as replyWithError. Sync callbacks keep their synchronous-throw semantics.
  • Consumed/pending bookkeeping now happens before callback resolution, so a dispatch pending on an async callback cannot be re-matched beyond its allowed times — consistent with how async data callbacks already behave (they mark consumption at dispatch time).
  • Types: MockReplyOptionsCallback may return a Promise of the reply options (extracted a named MockReplyOptions type).
  • Docs: MockPool.md — callback description + a new async example.
  • Tests: async happy path, defaultReplyHeaders/replyContentLength interaction, times() bookkeeping, invalid resolved format, and rejection propagation; tsd assertions for the async signature.

Features

  • MockInterceptor.reply() accepts an asynchronous reply options callback.

Bug Fixes

N/A

Breaking Changes and Deprecations

N/A

Status

🤖 Generated with Claude Code

Fixes nodejs#1348

reply(callback) assumed the callback returns a plain object, so an
async callback's promise passed the object check, spread into nothing,
and dispatch threw InvalidArgumentError('statusCode must be defined').

Extend the isPromise pattern introduced for async data callbacks
(nodejs#1758) to the reply options callback: resolve the dispatch data once
the promise settles, and surface rejections through onResponseError
since they can no longer throw synchronously from dispatch. Consumed
bookkeeping now happens before callback resolution so a pending async
callback cannot be re-matched beyond its allowed times, matching how
async data callbacks already behave.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@mcollina mcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.45%. Comparing base (3c662a5) to head (48ba2e5).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #5534   +/-   ##
=======================================
  Coverage   93.44%   93.45%           
=======================================
  Files         110      110           
  Lines       37329    37376   +47     
=======================================
+ Hits        34883    34928   +45     
- Misses       2446     2448    +2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@mcollina mcollina merged commit 6de5935 into nodejs:main Jul 9, 2026
36 checks passed
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

Successfully merging this pull request may close these issues.

Allow asynchronous mocking replies

3 participants