Skip to content

Commit

Permalink
fix: define property instead of assigning it in vi.stubGlobal (#2685)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Jan 16, 2023
1 parent 15aa015 commit 8a1d759
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
8 changes: 6 additions & 2 deletions packages/vitest/src/integrations/vi.ts
Expand Up @@ -259,8 +259,12 @@ class VitestUtils {
public stubGlobal(name: string | symbol | number, value: any) {
if (!this._stubsGlobal.has(name))
this._stubsGlobal.set(name, Object.getOwnPropertyDescriptor(globalThis, name))
// @ts-expect-error we can do anything!
globalThis[name] = value
Object.defineProperty(globalThis, name, {
value,
writable: true,
configurable: true,
enumerable: true,
})
return this
}

Expand Down
20 changes: 20 additions & 0 deletions test/core/test/stubs.test.ts
Expand Up @@ -5,12 +5,32 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
declare global {
// eslint-disable-next-line no-var
var __defined__: unknown
// eslint-disable-next-line no-var
var __setter__: unknown
}

describe('stubbing globals', () => {
beforeEach(() => {
delete globalThis.__defined__
if (globalThis.__setter__)
delete globalThis.__setter__
vi.unstubAllGlobals()
})

it('overrites setter', () => {
const descriptor = {
get: () => 'getter',
set: () => {},
configurable: true,
}
Object.defineProperty(globalThis, '__setter__', descriptor)
expect(__setter__).toBe('getter')
vi.stubGlobal('__setter__', 'stubbed')
expect(__setter__).toBe('stubbed')
expect(globalThis.__setter__).toBe('stubbed')
expect(Object.getOwnPropertyDescriptor(globalThis, '__setter__')).not.toBe(descriptor)
vi.unstubAllGlobals()
expect(__setter__).toBe('getter')
})

it('stubs and restores already defined value', () => {
Expand Down
3 changes: 1 addition & 2 deletions test/core/test/vi.spec.ts
Expand Up @@ -77,8 +77,7 @@ describe('testing vi utils', () => {
expect(state.config.clearMocks).toBe(false)
})

// TODO: it's unstable in CI, skip until resolved
test.skip('loads unloaded module', async () => {
test('loads unloaded module', async () => {
let mod: any
import('../src/timeout').then(m => mod = m)

Expand Down

0 comments on commit 8a1d759

Please sign in to comment.