|
| 1 | +import { getQueriesForElement, prettyDOM } from "@testing-library/dom"; |
| 2 | +import { hydrate as solidHydrate, render as solidRender } from "solid-js/web"; |
| 3 | +if (!process.env.STL_SKIP_AUTO_CLEANUP) { |
| 4 | + if (typeof afterEach === 'function') { |
| 5 | + afterEach(async () => { |
| 6 | + await cleanup(); |
| 7 | + }); |
| 8 | + // @ts-ignore |
| 9 | + } |
| 10 | + else if (typeof teardown === 'function') { |
| 11 | + // @ts-ignore |
| 12 | + teardown(async () => { |
| 13 | + await cleanup(); |
| 14 | + }); |
| 15 | + } |
| 16 | +} |
| 17 | +const mountedContainers = new Set(); |
| 18 | +function render(ui, { container, baseElement = container, queries, hydrate = false } = {}) { |
| 19 | + if (!baseElement) { |
| 20 | + // Default to document.body instead of documentElement to avoid output of potentially-large |
| 21 | + // head elements (such as JSS style blocks) in debug output. |
| 22 | + baseElement = document.body; |
| 23 | + } |
| 24 | + if (!container) { |
| 25 | + container = baseElement.appendChild(document.createElement("div")); |
| 26 | + } |
| 27 | + const dispose = hydrate |
| 28 | + ? solidHydrate(ui, container) |
| 29 | + : solidRender(ui, container); |
| 30 | + // We'll add it to the mounted containers regardless of whether it's actually |
| 31 | + // added to document.body so the cleanup method works regardless of whether |
| 32 | + // they're passing us a custom container or not. |
| 33 | + mountedContainers.add({ container, dispose }); |
| 34 | + return { |
| 35 | + container, |
| 36 | + baseElement, |
| 37 | + debug: (el = baseElement, maxLength, options) => Array.isArray(el) |
| 38 | + ? el.forEach(e => console.log(prettyDOM(e, maxLength, options))) |
| 39 | + : console.log(prettyDOM(el, maxLength, options)), |
| 40 | + unmount: dispose, |
| 41 | + asFragment: () => { |
| 42 | + if (typeof document.createRange === "function") { |
| 43 | + return document.createRange().createContextualFragment(container.innerHTML); |
| 44 | + } |
| 45 | + else { |
| 46 | + const template = document.createElement("template"); |
| 47 | + template.innerHTML = container.innerHTML; |
| 48 | + return template.content; |
| 49 | + } |
| 50 | + }, |
| 51 | + ...getQueriesForElement(baseElement, queries) |
| 52 | + }; |
| 53 | +} |
| 54 | +function cleanupAtContainer(ref) { |
| 55 | + const { container, dispose } = ref; |
| 56 | + dispose(); |
| 57 | + if (container.parentNode === document.body) { |
| 58 | + document.body.removeChild(container); |
| 59 | + } |
| 60 | + mountedContainers.delete(ref); |
| 61 | +} |
| 62 | +function cleanup() { |
| 63 | + mountedContainers.forEach(cleanupAtContainer); |
| 64 | +} |
| 65 | +export * from "@testing-library/dom"; |
| 66 | +export { render, cleanup }; |
0 commit comments