-
Notifications
You must be signed in to change notification settings - Fork 5k
Fix crash when Reflect.construct is used on mock functions returning non-objects #28532
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -837,6 +837,7 @@ JSC_DEFINE_HOST_FUNCTION(jsMockFunctionCall, (JSGlobalObject * lexicalGlobalObje | |
| return {}; | ||
| } | ||
|
|
||
| const bool isConstruct = !callframe->newTarget().isUndefined(); | ||
| JSC::ArgList args = JSC::ArgList(callframe); | ||
| JSValue thisValue = callframe->thisValue(); | ||
| JSC::JSArray* argumentsArray = nullptr; | ||
|
|
@@ -954,15 +955,24 @@ JSC_DEFINE_HOST_FUNCTION(jsMockFunctionCall, (JSGlobalObject * lexicalGlobalObje | |
| fn->returnValues.set(vm, fn, returnValuesArray); | ||
| } | ||
|
|
||
| if (isConstruct && !returnValue.isObject()) { | ||
| return JSValue::encode(thisValue.isObject() ? thisValue : JSC::constructEmptyObject(globalObject)); | ||
| } | ||
| return JSValue::encode(returnValue); | ||
| } | ||
| case JSMockImplementation::Kind::ReturnValue: { | ||
| JSValue returnValue = impl->underlyingValue.get(); | ||
| setReturnValue(createMockResult(vm, globalObject, "return"_s, returnValue)); | ||
| if (isConstruct && !returnValue.isObject()) { | ||
| return JSValue::encode(thisValue.isObject() ? thisValue : JSC::constructEmptyObject(globalObject)); | ||
| } | ||
| return JSValue::encode(returnValue); | ||
| } | ||
| case JSMockImplementation::Kind::ReturnThis: { | ||
| setReturnValue(createMockResult(vm, globalObject, "return"_s, thisValue)); | ||
| if (isConstruct && !thisValue.isObject()) { | ||
| return JSValue::encode(JSC::constructEmptyObject(globalObject)); | ||
| } | ||
| return JSValue::encode(thisValue); | ||
| } | ||
| case JSMockImplementation::Kind::RejectedValue: { | ||
|
|
@@ -978,6 +988,9 @@ JSC_DEFINE_HOST_FUNCTION(jsMockFunctionCall, (JSGlobalObject * lexicalGlobalObje | |
| } | ||
|
|
||
| setReturnValue(createMockResult(vm, globalObject, "return"_s, jsUndefined())); | ||
| if (isConstruct) { | ||
| return JSValue::encode(thisValue.isObject() ? thisValue : JSC::constructEmptyObject(globalObject)); | ||
| } | ||
| return JSValue::encode(jsUndefined()); | ||
| } | ||
|
|
||
|
Comment on lines
988
to
996
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟣 Pre-existing bug: in Extended reasoning...What the bug isIn auto lastImpl = thisObject->implementation.get(); // head of the once-queue
auto lastTail = thisObject->tail.get(); // tail of the once-queue
auto lastFallback = thisObject->fallbackImplmentation.get();
// ...
// synchronous restore:
thisObject->implementation.set(vm, thisObject, lastImpl); // correct
thisObject->tail.set(vm, thisObject, lastImpl); // BUG: should be lastTail
thisObject->fallbackImplmentation.set(vm, thisObject, lastFallback); // correct
The specific code pathThe async cleanup handler Why existing code does not prevent thisThe ImpactWhen a user has queued multiple once-implementations and then calls const m = jest.fn();
m.mockImplementationOnce(() => 1);
m.mockImplementationOnce(() => 2); // tail -> once(2), impl -> once(1)
m.withImplementation(() => 99, () => {});
// After sync restore: tail = once(1) (WRONG, should be once(2))
m.mockImplementationOnce(() => 3);
// pushImplOnce chains once(3) off once(1), but once(2) is now orphaned
// queue should be: once(1)->once(2)->once(3), but is: once(1)->once(3)Step-by-step proof
FixChange the synchronous restore to use thisObject->tail.set(vm, thisObject, lastTail); // was: lastImpl |
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import { expect, jest, test } from "bun:test"; | ||
|
|
||
| test("Reflect.construct on mock with non-object return value does not crash", () => { | ||
| const m = jest.fn(() => 42); | ||
| const result = Reflect.construct(m, []); | ||
| expect(result).toBeObject(); | ||
| expect(m.mock.results[0].value).toBe(42); | ||
| }); | ||
|
|
||
| test("Reflect.construct on mock with mockReturnValue does not crash", () => { | ||
| const m = jest.fn(); | ||
| m.mockReturnValue(123); | ||
| const result = Reflect.construct(m, []); | ||
| expect(result).toBeObject(); | ||
| expect(m.mock.results[0].value).toBe(123); | ||
| }); | ||
|
Comment on lines
+3
to
+16
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 Nitpick | 🔵 Trivial Assert receiver/prototype semantics in the primitive-return cases.
🧪 Suggested coverage additions test("Reflect.construct on mock with non-object return value does not crash", () => {
const m = jest.fn(() => 42);
const result = Reflect.construct(m, []);
expect(result).toBeObject();
+ expect(Object.getPrototypeOf(result)).toBe(m.prototype);
expect(m.mock.results[0].value).toBe(42);
});
@@
test("new on mock with non-object return value still works", () => {
const m = jest.fn(() => 42);
const result = new m();
expect(result).toBeObject();
+ expect(Object.getPrototypeOf(result)).toBe(m.prototype);
expect(m.mock.results[0].value).toBe(42);
});
+
+test("Reflect.construct preserves the supplied newTarget prototype", () => {
+ const m = jest.fn(() => 42);
+ function NewTarget() {}
+
+ const result = Reflect.construct(m, [], NewTarget);
+ expect(Object.getPrototypeOf(result)).toBe(NewTarget.prototype);
+});
+
+test("mockReturnThis under construction returns the receiver", () => {
+ const m = jest.fn().mockReturnThis();
+ const result = new m();
+
+ expect(Object.getPrototypeOf(result)).toBe(m.prototype);
+ expect(m.mock.results[0].value).toBe(result);
+});Also applies to: 25-30 🤖 Prompt for AI Agents |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟣 Pre-existing issue:
mock.mock.instancesis always an empty array in Bun becausefn->instancesis never written to anywhere injsMockFunctionCall. This PR addsisConstructdetection and makesReflect.constructa first-class supported path, so users will now naturally reach this gap when inspectingm.mock.instancesafter constructor calls.Extended reasoning...
What the bug is
mock.mock.instancesis supposed to record thethisvalue (the newly-constructed object) for every constructor invocation, matching Jest behavior. In Bun, thefn->instanceswrite-barrier field is declared, GC-visited, lazily initialized to an empty array, and exposed on themock.mockobject — but it is never written to during invocation. The result is thatm.mock.instancesis permanently[]regardless of how many times the mock is called withneworReflect.construct.The specific code path
In
jsMockFunctionCall(JSMockFunction.cpp), the function populatesfn->calls,fn->contexts,fn->invocationCallOrder, andfn->returnValuesfor every call, but there is no corresponding block that pushes tofn->instances. ThegetInstances()accessor (lines 419-424) lazily constructs the array on first access but no code path ever callsinstances->push(...)orputDirectIndex(...)on it.Why existing code does not prevent this
Searching the entire file confirms
fn->instancesonly appears in: the field declaration,clear(),getInstances(), the GC visitor, and the mock object structure initializer. There is no invocation-time write. The gap has always existed — before this PR,new m()also leftinstancesempty — but the PR officially supportsReflect.constructas a working code path and adds theisConstructflag, so users will now reasonably expectmock.mock.instancesto be populated afterReflect.construct(m, [])succeeds.Impact
Any code that inspects
m.mock.instances[n]to verify what object was constructed will always seeundefined(or findinstances.length === 0). This is a divergence from Jest:How to fix
When
isConstructis true, pushthisValue(or the fallback empty object) tofn->instancesat the same point calls and contexts are recorded. The simplest fix mirrors the contexts tracking block:Step-by-step proof
const m = jest.fn();— creates aJSMockFunction;fn->instancesis uninitialized (will be lazily created as[]).new m();—jsMockFunctionCallis invoked withcallframe->newTarget()set;isConstruct = true.fn->calls,fn->contexts,fn->invocationCallOrder.fn->instances.m.mock.instances→getInstances()returns the lazily-created empty[].m.mock.instances[0]→undefined. In Jest this would be the constructed object.This is pre-existing behavior unrelated to this PR, but the PR directly interacts with the affected code area and increases the surface for this issue by making
Reflect.constructsucceed where it previously crashed.