Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: define property instead of assigning it in vi.stubGlobal #2685

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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