cypress-ct-html
Version:
Cypress Component Testing for plain HTML/CSS/JS and Web Components
41 lines (40 loc) • 1.38 kB
JavaScript
import { getContainerEl, setupHooks } from "@cypress/mount-utils";
let dispose = () => void 0;
function cleanup() {
dispose === null || dispose === void 0 ? void 0 : dispose();
}
export function mount(component) {
cleanup();
if (typeof component === "string") {
const template = document.createElement("template");
template.innerHTML = component;
if (template.content.children.length > 1)
throw new Error("The provided HTML string must have a single root element");
component = template.content.firstElementChild;
if (!component)
throw new Error("The provided HTML string was not able to be parsed into a valid HTML element");
}
const root = getContainerEl();
render(component, root);
dispose = () => {
render(null, root);
};
return cy
.wrap(root, { log: false })
.wait(0, { log: false })
.children({ log: false })
.first({ log: false })
.then((element) => {
const name = element.prop("tagName").toLowerCase();
// safe cast for current html element
const el = document.getElementsByTagName(name)[0];
return cy.wrap(el, { log: false });
});
}
function render(component, root) {
root.innerHTML = "";
if (!component)
return;
root.appendChild(component);
}
setupHooks(cleanup);