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();