Skip to content

fix: throw a clear error when throwArg index equals the argument count#2743

Open
spokodev wants to merge 1 commit into
sinonjs:mainfrom
spokodev:fix/throwarg-index-off-by-one
Open

fix: throw a clear error when throwArg index equals the argument count#2743
spokodev wants to merge 1 commit into
sinonjs:mainfrom
spokodev:fix/throwarg-index-off-by-one

Conversation

@spokodev

@spokodev spokodev commented Jul 1, 2026

Copy link
Copy Markdown

spyCall.throwArg(pos) (and the aggregate spy.throwArg(pos)) make a recorded call throw one of its own arguments. The bounds guard is off by one, so calling throwArg(pos) with pos equal to the number of recorded arguments throws undefined instead of the intended TypeError.

Valid indices are 0 .. args.length - 1. The guard pos > this.args.length lets pos === args.length through to throw this.args[pos], where this.args[pos] is undefined. The thrown undefined cannot be inspected as an Error, and test frameworks report it as "no exception was thrown", which hides the real off-by-one.

The sibling helpers (callArg, callArgOn, and the rest) and the stub-time throwsArg (via ensureArgs in behavior.js, which uses >=) already reject an out-of-range index with a clear error. PR #1848 established that these argument-index helpers should throw a clear TypeError rather than yield undefined.

Fix

Change the guard in src/sinon/proxy-call.js from > to >=, matching ensureArgs:

if (pos >= this.args.length) {

Added a call.throwArg block to test/src/proxy-call-test.js: it throws the argument at a valid index, and throws a clear TypeError when the index equals or exceeds the argument count. The equal-to-count case fails before this change; the full test/src suite (1497) stays green.

spyCall.throwArg(pos) guarded with pos > this.args.length, so calling it
with pos equal to the number of recorded arguments slipped past the guard
and reached throw this.args[pos], throwing undefined instead of the
intended TypeError. A thrown undefined cannot be inspected as an Error and
is reported by test frameworks as no exception thrown.

Use >= to match ensureArgs in behavior.js and the sibling callArg helpers,
which already reject an out-of-range index with a clear error.
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.

1 participant