aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/bun.js/bindings/JSMockFunction.cpp12
-rw-r--r--test/js/bun/test/mock-fn.test.js14
2 files changed, 22 insertions, 4 deletions
diff --git a/src/bun.js/bindings/JSMockFunction.cpp b/src/bun.js/bindings/JSMockFunction.cpp
index fbfcf0c9e..33922c2b7 100644
--- a/src/bun.js/bindings/JSMockFunction.cpp
+++ b/src/bun.js/bindings/JSMockFunction.cpp
@@ -569,15 +569,19 @@ extern "C" EncodedJSValue JSMock__jsSpyOn(JSC::JSGlobalObject* lexicalGlobalObje
// easymode: regular property or missing property
if (!hasValue || slot.isValue()) {
+ JSValue value = jsUndefined();
+ if (hasValue) {
+ value = slot.getValue(globalObject, propertyKey);
+ if (jsDynamicCast<JSMockFunction*>(value)) {
+ return JSValue::encode(value);
+ }
+ }
+
auto* mock = JSMockFunction::create(vm, globalObject, globalObject->mockModule.mockFunctionStructure.getInitializedOnMainThread(globalObject), CallbackKind::GetterSetter);
mock->spyTarget = JSC::Weak<JSObject>(object, &weakValueHandleOwner(), nullptr);
mock->spyIdentifier = propertyKey.isSymbol() ? Identifier::fromUid(vm, propertyKey.uid()) : Identifier::fromString(vm, propertyKey.publicName());
mock->spyAttributes = hasValue ? slot.attributes() : 0;
unsigned attributes = 0;
- JSValue value = jsUndefined();
-
- if (hasValue)
- value = slot.getValue(globalObject, propertyKey);
if (hasValue && ((slot.attributes() & PropertyAttribute::Function) != 0 || (value.isCell() && value.isCallable()))) {
if (hasValue)
diff --git a/test/js/bun/test/mock-fn.test.js b/test/js/bun/test/mock-fn.test.js
index 8504e3d70..ef3c4b7d3 100644
--- a/test/js/bun/test/mock-fn.test.js
+++ b/test/js/bun/test/mock-fn.test.js
@@ -603,5 +603,19 @@ describe("spyOn", () => {
});
}
+ test("spyOn twice works", () => {
+ var obj = {
+ original() {
+ return 42;
+ },
+ };
+ const _original = obj.original;
+ const fn = spyOn(obj, "original");
+ const fn2 = spyOn(obj, "original");
+ expect(fn).toBe(obj.original);
+ expect(fn2).toBe(fn);
+ expect(fn).not.toBe(_original);
+ });
+
// spyOn does not work with getters/setters yet.
});