Skip to content
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

Populate result with new operator if new.target is defined #30

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/spy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ export function spy<A extends any[], R>(cb?: (...args: A) => R): SpyFn<A, R> {
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
Expand Down
18 changes: 18 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})