Skip to main content

setGlobal()

setGlobal<T>(key, value): () => void

Sets a value on globalThis and returns a restore function.

note

Always call the returned restore function. Auto-restored after each test if forgotten.


Type Parameters​

T: T​

The value type.


Parameters​

key: string​

The key to set on globalThis.

value: T​

The value to set.


Returns​

A restore function.

(): void

Returns: void​


Since​

2.0.0


Example​

const restore = setGlobal('fetch', vi.fn());
// ... tests ...
restore();

Use Cases​

Inject global mocks πŸ“Œβ€‹

Temporarily set a global variable (like fetch or IntersectionObserver). Useful for mocking browser APIs in a test environment.

const restore = setGlobal('fetch', vi.fn(() => 
Promise.resolve({ ok: true, json: () => ({}) })
));

await fetchData('/api/users');
expect(globalThis.fetch).toHaveBeenCalled();
restore();

Mock missing APIs​

Polyfill APIs that don't exist in Node.js test environment.

const restore = setGlobal('IntersectionObserver', MockIntersectionObserver);

const component = mount(<LazyImage />);
expect(component).toBeDefined();
restore();