diff --git a/src/spy.ts b/src/spy.ts index dac6cb6..099d72b 100644 --- a/src/spy.ts +++ b/src/spy.ts @@ -56,7 +56,9 @@ export function spy(cb?: (...args: A) => R): SpyFn { let type: 'ok' | 'error' = 'ok' if (fn.impl) { try { - result = fn.impl.apply(this, args) + result = new.target + ? new (fn.impl as any)(args) + : fn.impl.apply(this, args) type = 'ok' } catch (err: any) { result = err diff --git a/test/index.test.ts b/test/index.test.ts index d5fa680..164a07d 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -685,3 +685,21 @@ test('does not await on non-promise values that contain .then', async () => { const spiedResult = spied().addValue('Hello').addValue('World') expect(spiedResult).toStrictEqual(originalResult) }) + +test('spyOn with new.target', () => { + const fn = { + fnFunc: () => {}, + fnClass: class FnClass {}, + } + + spyOn(fn, 'fnFunc').willCall(function () { + expect(new.target).toBeUndefined() + }) + spyOn(fn, 'fnClass').willCall(function () { + expect(new.target).toBeDefined() + return fn.fnClass + }) + + fn.fnFunc() + new fn.fnClass() +})