Skip to content

Commit

Permalink
fix(hasConfigurableGlobal): handle existing globals with undefined va…
Browse files Browse the repository at this point in the history
…lue (#669)

Co-authored-by: Artem Zakharchenko <[email protected]>
  • Loading branch information
Afsoon and kettanaito authored Nov 3, 2024
1 parent 7aff641 commit f2ae132
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/utils/hasConfigurableGlobal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,30 @@ it('returns false if the global property does not exist', () => {
expect(hasConfigurableGlobal('_non-existing')).toBe(false)
})

it('returns false for existing global with undefined as a value', () => {
Object.defineProperty(global, '_existsAndUndefined', {
value: undefined,
configurable: true,
})
expect(hasConfigurableGlobal('_existsAndUndefined')).toBe(false)
})

it('returns false for existing global with null as a value', () => {
Object.defineProperty(global, '_existsAndNull', {
value: null,
configurable: true,
})
expect(hasConfigurableGlobal('_existsAndNull')).toBe(false)
})

it('returns false for existing global with a getter that returns undefined', () => {
Object.defineProperty(global, '_existsGetterUndefined', {
get: () => undefined,
configurable: true,
})
expect(hasConfigurableGlobal('_existsGetterUndefined')).toBe(false)
})

it('returns false and prints an error for implicitly non-configurable global property', () => {
Object.defineProperty(global, '_implicitlyNonConfigurable', {
value: 'something',
Expand Down
14 changes: 14 additions & 0 deletions src/utils/hasConfigurableGlobal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,24 @@
export function hasConfigurableGlobal(propertyName: string): boolean {
const descriptor = Object.getOwnPropertyDescriptor(globalThis, propertyName)

// The property is not set at all.
if (typeof descriptor === 'undefined') {
return false
}

// The property is set to a getter that returns undefined.
if (
typeof descriptor.get === 'function' &&
typeof descriptor.get() === 'undefined'
) {
return false
}

// The property is set to a value equal to undefined.
if (typeof descriptor.get === 'undefined' && descriptor.value == null) {
return false
}

if (typeof descriptor.set === 'undefined' && !descriptor.configurable) {
console.error(
`[MSW] Failed to apply interceptor: the global \`${propertyName}\` property is non-configurable. This is likely an issue with your environment. If you are using a framework, please open an issue about this in their repository.`
Expand Down

0 comments on commit f2ae132

Please sign in to comment.