Skip to main content

mockDocument()

mockDocument(overrides?): MockDocumentResult

Creates a mock document object on globalThis for Node.js tests.

note

Always call restore() for cleanup. Auto-restored after each test if forgotten.


Parameters​

overrides?: Partial<Document> = {}​

Properties to set on the mock document.


Returns: MockDocumentResult​

Object containing the mock document and restore function.


Since​

2.0.0


Example​

const { document, restore } = mockDocument({
querySelector: vi.fn(() => null),
});
restore();

Use Cases​

Mock document properties πŸ“Œβ€‹

Override document properties or methods in a test environment. Essential for testing code that interacts with the global document object.

const { restore } = mockDocument({
title: 'Test Page',
getElementById: vi.fn(() => mockElement)
});

expect(document.title).toBe('Test Page');
restore();

Simulate missing elements​

Test fallback behavior when DOM elements don't exist.

const { restore } = mockDocument({
querySelector: vi.fn(() => null)
});

const result = initComponent('#missing');
expect(result).toBeNull();
restore();

MockDocumentResult​

Interface

Result of mockDocument().


Since​

2.0.0


Properties​

document: Document​

restore(): () => void​

Returns​

void