Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 3 additions & 21 deletions tests/minidom/registerDomGlobals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,22 +52,14 @@ export function registerDomGlobals(
assignGlobal(globals, 'Node', win.Node)
assignGlobal(globals, 'Element', win.Element)
assignGlobal(globals, 'HTMLElement', win.HTMLElement)
assignGlobal(
globals,
'HTMLSlotElement',
(document as Document).createElement('slot').constructor,
)
assignGlobal(globals, 'HTMLSlotElement', win.HTMLSlotElement)
assignGlobal(globals, 'DocumentFragment', win.DocumentFragment)
assignGlobal(globals, 'CustomEvent', win.CustomEvent)
assignGlobal(globals, 'Event', win.Event)
assignGlobal(globals, 'MouseEvent', win.MouseEvent)
assignGlobal(globals, 'Comment', createCommentConstructor(document))
assignGlobal(globals, 'Comment', win.Comment)
assignGlobal(globals, 'Text', win.Text)
assignGlobal(
globals,
'HTMLTemplateElement',
(document as Document).createElement('template').constructor,
)
assignGlobal(globals, 'HTMLTemplateElement', win.HTMLTemplateElement)

const windowCss = win.CSS as { escape?: unknown } | undefined
assignGlobal(
Expand Down Expand Up @@ -107,13 +99,3 @@ export function ensureDomGlobals(): () => void {
const { document, window } = parseHtml('<html><body></body></html>')
return registerDomGlobals(window, document)
}

function createCommentConstructor(document: unknown): typeof Comment {
const doc = document as Document
const prototype = Object.getPrototypeOf(doc.createComment(''))
const CommentShim = function Comment(this: Comment, data?: string) {
return doc.createComment(data ?? '')
} as unknown as typeof Comment
CommentShim.prototype = prototype
return CommentShim
}
30 changes: 29 additions & 1 deletion tests/setup.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
import { afterAll, afterEach, beforeEach } from 'vitest'

import { ensureDomGlobals } from './minidom/registerDomGlobals'

ensureDomGlobals()
const restoreDomGlobals = ensureDomGlobals()

function resetDomState() {
const doc = globalThis.document as
| (Document & { head?: ParentNode | null; body?: ParentNode | null })
| undefined
doc?.head?.replaceChildren()
doc?.body?.replaceChildren()
if ('localStorage' in globalThis) {
;(globalThis.localStorage as Storage).clear()
}
if ('sessionStorage' in globalThis) {
;(globalThis.sessionStorage as Storage).clear()
}
}

beforeEach(() => {
resetDomState()
})

afterEach(() => {
resetDomState()
})

afterAll(() => {
restoreDomGlobals()
})