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