Skip to content

Commit ac1d92f

Browse files
authored
fix(spy): don't fail when spying on static getters (#8589)
1 parent 500aa48 commit ac1d92f

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

packages/spy/src/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,11 @@ export function spyOn<T extends object, K extends keyof T>(
264264
const originalType = typeof originalImplementation
265265

266266
assert(
267-
originalType === 'function',
267+
// allow only functions
268+
originalType === 'function'
269+
// or allow getter/setter on a static value,
270+
// e.g. spyOn({ value: 3 }, 'value', 'get')
271+
|| (accessType !== 'value' && original == null),
268272
`vi.spyOn() can only spy on a function. Received ${originalType}.`,
269273
)
270274

test/core/test/mocking/vi-spyOn.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,30 @@ describe('vi.spyOn() settings', () => {
282282
expect(spy2.mock.calls).toEqual(spy1.mock.calls)
283283
})
284284

285+
test('vi.spyOn() when spying on a static getter spy returns the same spy', () => {
286+
const object = createObject()
287+
const spy1 = vi.spyOn(object, 'static', 'get')
288+
const spy2 = vi.spyOn(object, 'static', 'get')
289+
expect(spy1).toBe(spy2)
290+
291+
const _example = object.static
292+
expect(spy2).toHaveBeenCalledTimes(1)
293+
expect(spy1).toHaveBeenCalledTimes(1)
294+
expect(spy2.mock.calls).toEqual(spy1.mock.calls)
295+
})
296+
297+
test('vi.spyOn() when spying on a static setter spy returns the same spy', () => {
298+
const object = createObject()
299+
const spy1 = vi.spyOn(object, 'static', 'set')
300+
const spy2 = vi.spyOn(object, 'static', 'set')
301+
expect(spy1).toBe(spy2)
302+
303+
object.static = 33
304+
expect(spy2).toHaveBeenCalledTimes(1)
305+
expect(spy1).toHaveBeenCalledTimes(1)
306+
expect(spy2.mock.calls).toEqual(spy1.mock.calls)
307+
})
308+
285309
test('vi.spyOn() can spy on multiple class instances without intervention', () => {
286310
class Example {
287311
method() {
@@ -668,5 +692,6 @@ function createObject() {
668692
set getter(value: number) {
669693
getterValue = value
670694
},
695+
static: 42,
671696
}
672697
}

0 commit comments

Comments
 (0)