Skip to content

Commit d951e63

Browse files
authored
fix(spy): use primordials to allow spying on builtins (#11837)
1 parent 289caab commit d951e63

3 files changed

Lines changed: 262 additions & 62 deletions

File tree

‎packages/spy/src/index.ts‎

Lines changed: 94 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,29 @@ import type {
1313
Procedure,
1414
Properties,
1515
} from './types'
16+
import {
17+
ArrayPrototypeAt,
18+
ArrayPrototypePush,
19+
ArrayPrototypeShift,
20+
FinalizationRegistryPrototypeRegister,
21+
ObjectDefineProperty,
22+
ObjectGetOwnPropertyDescriptor,
23+
ObjectGetPrototypeOf,
24+
ObjectSetPrototypeOf,
25+
ReflectApply,
26+
ReflectConstruct,
27+
ReflectDeleteProperty,
28+
ReflectOwnKeys,
29+
SetPrototypeAdd,
30+
SetPrototypeClear,
31+
SetPrototypeDelete,
32+
SetPrototypeHas,
33+
StringPrototypeIncludes,
34+
WeakMapPrototypeGet,
35+
WeakMapPrototypeSet,
36+
WeakRef,
37+
WeakRefPrototypeDeref,
38+
} from './primordials'
1639

1740
export function isMockFunction(fn: any): fn is Mock {
1841
return typeof fn === 'function' && '_isMockFunction' in fn && fn._isMockFunction === true
@@ -27,30 +50,28 @@ const DIRTY_MOCK_STATES = new Set<MockRef>()
2750
// Mocks whose implementation, once-queue or name changed since their last
2851
// `mockReset()`, so `resetAllMocks()` only visits mocks that are not already reset
2952
const DIRTY_MOCK_CONFIGS = new Set<MockRef>()
30-
// a test may spy on `Set.prototype.add`, and the spy itself marks mocks dirty
31-
const addToSet = Set.prototype.add
3253
const MOCK_REFS = new WeakMap<Mock<Procedure | Constructable>, MockRef>()
3354
const MOCK_FINALIZER = new FinalizationRegistry<MockRef>((ref) => {
34-
DIRTY_MOCK_STATES.delete(ref)
35-
DIRTY_MOCK_CONFIGS.delete(ref)
55+
SetPrototypeDelete(DIRTY_MOCK_STATES, ref)
56+
SetPrototypeDelete(DIRTY_MOCK_CONFIGS, ref)
3657
})
3758
const MOCK_CONFIGS = new WeakMap<Mock<Procedure | Constructable>, MockConfig>()
3859
const MOCKS_BY_STATE = new WeakMap<MockContext, Mock<Procedure | Constructable>>()
3960

4061
function markDirty(set: Set<MockRef>, mock: Mock<Procedure | Constructable>): void {
41-
let ref = MOCK_REFS.get(mock)
62+
let ref = WeakMapPrototypeGet(MOCK_REFS, mock)
4263
if (!ref) {
4364
ref = new WeakRef(mock)
44-
MOCK_REFS.set(mock, ref)
45-
MOCK_FINALIZER.register(mock, ref)
65+
WeakMapPrototypeSet(MOCK_REFS, mock, ref)
66+
FinalizationRegistryPrototypeRegister(MOCK_FINALIZER, mock, ref)
4667
}
47-
addToSet.call(set, ref)
68+
SetPrototypeAdd(set, ref)
4869
}
4970

5071
function unmarkDirty(set: Set<MockRef>, mock: Mock<Procedure | Constructable>): void {
51-
const ref = MOCK_REFS.get(mock)
72+
const ref = WeakMapPrototypeGet(MOCK_REFS, mock)
5273
if (ref) {
53-
set.delete(ref)
74+
SetPrototypeDelete(set, ref)
5475
}
5576
}
5677

@@ -59,11 +80,11 @@ function forEachDirty(
5980
fn: (mock: Mock<Procedure | Constructable>) => void,
6081
): void {
6182
for (const ref of set) {
62-
const mock = ref.deref()
83+
const mock = WeakRefPrototypeDeref(ref)
6384
if (mock) {
6485
fn(mock)
6586
} else {
66-
set.delete(ref)
87+
SetPrototypeDelete(set, ref)
6788
}
6889
}
6990
}
@@ -80,7 +101,7 @@ export function createMockInstance(
80101
} = options
81102

82103
if (restore) {
83-
MOCK_RESTORE.add(restore)
104+
SetPrototypeAdd(MOCK_RESTORE, restore)
84105
}
85106

86107
const config = getDefaultConfig(originalImplementation)
@@ -92,7 +113,7 @@ export function createMockInstance(
92113
...options,
93114
})
94115
const mockLength = (mockImplementation || originalImplementation)?.length ?? 0
95-
Object.defineProperty(mock, 'length', {
116+
ObjectDefineProperty(mock, 'length', {
96117
writable: true,
97118
enumerable: false,
98119
value: mockLength,
@@ -104,8 +125,8 @@ export function createMockInstance(
104125
if (resetToMockName) {
105126
config.mockName = mock.name || 'vi.fn()'
106127
}
107-
MOCK_CONFIGS.set(mock, config)
108-
MOCKS_BY_STATE.set(state, mock)
128+
WeakMapPrototypeSet(MOCK_CONFIGS, mock, config)
129+
WeakMapPrototypeSet(MOCKS_BY_STATE, state, mock)
109130

110131
mock._isMockFunction = true
111132
mock.getMockImplementation = () => {
@@ -127,7 +148,7 @@ export function createMockInstance(
127148
}
128149
}
129150

130-
Object.defineProperty(mock, 'mock', {
151+
ObjectDefineProperty(mock, 'mock', {
131152
configurable: false,
132153
enumerable: true,
133154
writable: false,
@@ -143,7 +164,7 @@ export function createMockInstance(
143164

144165
mock.mockImplementationOnce = function mockImplementationOnce(implementation) {
145166
markDirty(DIRTY_MOCK_CONFIGS, mock)
146-
config.onceMockImplementations.push(implementation)
167+
ArrayPrototypePush(config.onceMockImplementations, implementation)
147168
updateMockPrototype()
148169
return mock
149170
}
@@ -433,16 +454,16 @@ export function spyOn<T extends object, K extends keyof any>(
433454
delete desc.writable // getter/setter can't have writable attribute at all
434455
}
435456
;(desc as PropertyDescriptor)[accessType] = cb
436-
Object.defineProperty(object, key, desc)
457+
ObjectDefineProperty(object, key, desc)
437458
}
438459

439460
const restore = () => {
440461
// if method is defined on the prototype, we can just remove it from
441462
// the current object instead of redefining a copy of it
442463
if (originalDescriptorObject !== object) {
443-
Reflect.deleteProperty(object, key)
464+
ReflectDeleteProperty(object, key)
444465
} else if (originalDescriptor && !original) {
445-
Object.defineProperty(object, key, originalDescriptor)
466+
ObjectDefineProperty(object, key, originalDescriptor)
446467
} else {
447468
reassign(original)
448469
}
@@ -461,9 +482,9 @@ export function spyOn<T extends object, K extends keyof any>(
461482
error instanceof TypeError &&
462483
Symbol.toStringTag &&
463484
(object as any)[Symbol.toStringTag] === 'Module' &&
464-
(error.message.includes('Cannot redefine property') ||
465-
error.message.includes('Cannot replace module namespace') ||
466-
error.message.includes("can't redefine non-configurable property"))
485+
(StringPrototypeIncludes(error.message, 'Cannot redefine property') ||
486+
StringPrototypeIncludes(error.message, 'Cannot replace module namespace') ||
487+
StringPrototypeIncludes(error.message, "can't redefine non-configurable property"))
467488
) {
468489
throw new TypeError(
469490
`Cannot spy on export "${String(key)}". Module namespace is not configurable in ESM. See: https://vitest.dev/guide/mocking/modules#mocking-a-module`,
@@ -481,17 +502,17 @@ function getDescriptor(
481502
obj: any,
482503
method: string | symbol | number,
483504
): [any, PropertyDescriptor] | undefined {
484-
const objDescriptor = Object.getOwnPropertyDescriptor(obj, method)
505+
const objDescriptor = ObjectGetOwnPropertyDescriptor(obj, method)
485506
if (objDescriptor) {
486507
return [obj, objDescriptor]
487508
}
488-
let currentProto = Object.getPrototypeOf(obj)
509+
let currentProto = ObjectGetPrototypeOf(obj)
489510
while (currentProto !== null) {
490-
const descriptor = Object.getOwnPropertyDescriptor(currentProto, method)
511+
const descriptor = ObjectGetOwnPropertyDescriptor(currentProto, method)
491512
if (descriptor) {
492513
return [currentProto, descriptor]
493514
}
494-
currentProto = Object.getPrototypeOf(currentProto)
515+
currentProto = ObjectGetPrototypeOf(currentProto)
495516
}
496517
}
497518

@@ -520,7 +541,7 @@ function createMock({
520541
const pseudoOriginal = mockImplementation // init with vi.fn(Klass)
521542
const name = (mockName || original?.name || 'Mock') as string
522543
const noopImplementation = function () {}
523-
const prototypeMock = prototypeState && MOCKS_BY_STATE.get(prototypeState)
544+
const prototypeMock = prototypeState && WeakMapPrototypeGet(MOCKS_BY_STATE, prototypeState)
524545
const namedObject: Record<string, Mock<Procedure | Constructable>> = {
525546
// to keep the name of the function intact
526547
[name]: function (this: any, ...args: any[]) {
@@ -553,9 +574,9 @@ function createMock({
553574
const [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState)
554575

555576
const implementation: Procedure | Constructable =
556-
config.onceMockImplementations.shift() ||
577+
ArrayPrototypeShift(config.onceMockImplementations) ||
557578
config.mockImplementation ||
558-
prototypeConfig?.onceMockImplementations.shift() ||
579+
(prototypeConfig && ArrayPrototypeShift(prototypeConfig.onceMockImplementations)) ||
559580
prototypeConfig?.mockImplementation ||
560581
original ||
561582
noopImplementation
@@ -576,7 +597,7 @@ function createMock({
576597
implementation === noopImplementation ? undefined : implementation,
577598
)
578599
}
579-
returnValue = Reflect.construct(implementation, args, new.target)
600+
returnValue = ReflectConstruct(implementation, args, new.target)
580601

581602
// jest calls this before the implementation, but we have to resolve this _after_
582603
// because we cannot do it before the `Reflect.construct` called the custom implementation.
@@ -592,7 +613,9 @@ function createMock({
592613

593614
const isMock = isMockFunction(prototypeMock)
594615
const prototypeState = isMock ? prototypeMock.mock : undefined
595-
const prototypeConfig = isMock ? MOCK_CONFIGS.get(prototypeMock) : undefined
616+
const prototypeConfig = isMock
617+
? WeakMapPrototypeGet(MOCK_CONFIGS, prototypeMock)
618+
: undefined
596619
returnValue[prop] = createMockInstance({
597620
originalImplementation: keepMembersImplementation
598621
? prototypeConfig?.mockOriginal
@@ -603,12 +626,15 @@ function createMock({
603626
})
604627
}
605628
} else {
606-
returnValue = (implementation as Procedure).apply(this, args)
629+
returnValue = ReflectApply(implementation, this, args)
607630
}
608631
} catch (error: any) {
609632
thrownValue = error
610633
didThrow = true
611-
if (error instanceof TypeError && error.message.includes('is not a constructor')) {
634+
if (
635+
error instanceof TypeError &&
636+
StringPrototypeIncludes(error.message, 'is not a constructor')
637+
) {
612638
console.warn(
613639
`[vitest] The ${namedObject[name].getMockName()} mock did not use 'function' or 'class' in its implementation, see https://vitest.dev/api/vi#vi-spyon for examples.`,
614640
)
@@ -681,46 +707,55 @@ function reparentMockPrototype(
681707
// function) reverts the chain to `Object.prototype`, the parent every mock
682708
// is created with
683709
const parent = (implementation as Constructable | undefined)?.prototype ?? Object.prototype
684-
if (mockPrototype !== parent && Object.getPrototypeOf(mockPrototype) !== parent) {
685-
Object.setPrototypeOf(mockPrototype, parent)
710+
if (mockPrototype !== parent && ObjectGetPrototypeOf(mockPrototype) !== parent) {
711+
ObjectSetPrototypeOf(mockPrototype, parent)
686712
}
687713
}
688714

689715
function registerCalls(args: unknown[], state: MockContext, prototypeState?: MockContext) {
690-
state.calls.push(args)
691-
prototypeState?.calls.push(args)
716+
ArrayPrototypePush(state.calls, args)
717+
if (prototypeState) {
718+
ArrayPrototypePush(prototypeState.calls, args)
719+
}
692720
}
693721

694722
function registerInvocationOrder(order: number, state: MockContext, prototypeState?: MockContext) {
695-
state.invocationCallOrder.push(order)
696-
prototypeState?.invocationCallOrder.push(order)
723+
ArrayPrototypePush(state.invocationCallOrder, order)
724+
if (prototypeState) {
725+
ArrayPrototypePush(prototypeState.invocationCallOrder, order)
726+
}
697727
}
698728

699729
function registerResult(
700730
result: MockResult<Procedure>,
701731
state: MockContext,
702732
prototypeState?: MockContext,
703733
) {
704-
state.results.push(result)
705-
prototypeState?.results.push(result)
734+
ArrayPrototypePush(state.results, result)
735+
if (prototypeState) {
736+
ArrayPrototypePush(prototypeState.results, result)
737+
}
706738
}
707739

708740
function registerSettledResult(
709741
result: MockSettledResult<Procedure>,
710742
state: MockContext,
711743
prototypeState?: MockContext,
712744
) {
713-
state.settledResults.push(result)
714-
prototypeState?.settledResults.push(result)
745+
ArrayPrototypePush(state.settledResults, result)
746+
if (prototypeState) {
747+
ArrayPrototypePush(prototypeState.settledResults, result)
748+
}
715749
}
716750

717751
function registerInstance(
718752
instance: MockReturnType<Procedure>,
719753
state: MockContext,
720754
prototypeState?: MockContext,
721755
) {
722-
const instanceIndex = state.instances.push(instance)
723-
const instancePrototypeIndex = prototypeState?.instances.push(instance)
756+
const instanceIndex = ArrayPrototypePush(state.instances, instance)
757+
const instancePrototypeIndex =
758+
prototypeState && ArrayPrototypePush(prototypeState.instances, instance)
724759
return [instanceIndex, instancePrototypeIndex] as const
725760
}
726761

@@ -729,8 +764,9 @@ function registerContext(
729764
state: MockContext,
730765
prototypeState?: MockContext,
731766
) {
732-
const contextIndex = state.contexts.push(context)
733-
const contextPrototypeIndex = prototypeState?.contexts.push(context)
767+
const contextIndex = ArrayPrototypePush(state.contexts, context)
768+
const contextPrototypeIndex =
769+
prototypeState && ArrayPrototypePush(prototypeState.contexts, context)
734770
return [contextIndex, contextPrototypeIndex] as const
735771
}
736772

@@ -747,7 +783,7 @@ function copyOriginalStaticProperties(
747783
continue
748784
}
749785

750-
Object.defineProperty(mock, key, descriptor)
786+
ObjectDefineProperty(mock, key, descriptor)
751787
}
752788
}
753789

@@ -759,21 +795,17 @@ const ignoreProperties = new Set<string | symbol>([
759795
])
760796

761797
function getAllProperties(original: Procedure | Constructable) {
762-
const properties = new Set<string | symbol>()
798+
const properties: (string | symbol)[] = []
763799
const descriptors: Record<string | symbol, PropertyDescriptor | undefined> = {}
764800
while (original && original !== Object.prototype && original !== Function.prototype) {
765-
const ownProperties = [
766-
...Object.getOwnPropertyNames(original),
767-
...Object.getOwnPropertySymbols(original),
768-
]
769-
for (const prop of ownProperties) {
770-
if (descriptors[prop] || ignoreProperties.has(prop)) {
801+
for (const prop of ReflectOwnKeys(original)) {
802+
if (descriptors[prop] || SetPrototypeHas(ignoreProperties, prop)) {
771803
continue
772804
}
773-
properties.add(prop)
774-
descriptors[prop] = Object.getOwnPropertyDescriptor(original, prop)
805+
ArrayPrototypePush(properties, prop)
806+
descriptors[prop] = ObjectGetOwnPropertyDescriptor(original, prop)
775807
}
776-
original = Object.getPrototypeOf(original)
808+
original = ObjectGetPrototypeOf(original)
777809
}
778810
return {
779811
properties,
@@ -799,7 +831,7 @@ function getDefaultState(): MockContext {
799831
settledResults: [],
800832
results: [],
801833
get lastCall() {
802-
return state.calls.at(-1)
834+
return ArrayPrototypeAt(state.calls, -1)
803835
},
804836
}
805837
return state
@@ -809,7 +841,7 @@ export function restoreAllMocks(): void {
809841
for (const restore of MOCK_RESTORE) {
810842
restore()
811843
}
812-
MOCK_RESTORE.clear()
844+
SetPrototypeClear(MOCK_RESTORE)
813845
}
814846

815847
export function clearAllMocks(): void {

0 commit comments

Comments
 (0)