Skip to content

Commit

Permalink
feat: allow using "new" keyword with a spy
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Feb 7, 2023
1 parent 4b285a0 commit 2b6aa99
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
7 changes: 5 additions & 2 deletions src/spy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,12 @@ export interface SpyImpl<A extends any[] = any[], R = any> extends Spy<A, R> {

export interface SpyFn<A extends any[] = any[], R = any> extends Spy<A, R> {
(...args: A): R
new (...args: A): R
}

export function spy<A extends any[], R>(cb?: (...args: A) => R): SpyFn<A, R> {
export function spy<A extends any[], R>(
cb?: ((...args: A) => R) | { new (...args: A): R }
): SpyFn<A, R> {
assert(
isType('function', cb) || isType('undefined', cb),
'cannot spy on a non-function value'
Expand Down Expand Up @@ -100,7 +103,7 @@ export function spy<A extends any[], R>(cb?: (...args: A) => R): SpyFn<A, R> {
fn.calls = []
}
reset()
fn.impl = cb
fn.impl = cb as any
fn.reset = reset
fn.nextError = (error: any) => {
fn.next = ['error', error]
Expand Down
20 changes: 19 additions & 1 deletion test/class.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ describe('class mock', () => {
expect(() => new fnArrow()).toThrowError()
})

test('respects new.target', () => {
test('respects new.target in a function', () => {
let target: unknown = null
let args: unknown[] = []
const fnScoped = spy(function (...fnArgs: unknown[]) {
Expand All @@ -43,4 +43,22 @@ describe('class mock', () => {
expect(args).toEqual(['some', 'text', 1])
expect(fnScoped.calls).toEqual([['some', 'text', 1]])
})

test('respects new.target in a class', () => {
let target: unknown = null
let args: unknown[] = []
const fnScoped = spy(
class {
constructor(...fnArgs: unknown[]) {
target = new.target
args = fnArgs
}
}
)

new fnScoped('some', 'text', 1)
expect(target).toBeTypeOf('function')
expect(args).toEqual(['some', 'text', 1])
expect(fnScoped.calls).toEqual([['some', 'text', 1]])
})
})

0 comments on commit 2b6aa99

Please sign in to comment.