Skip to content

Instantly share code, notes, and snippets.

@dirv
Last active October 20, 2021 13:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dirv/838d6ec201d21af378154357c0e033d7 to your computer and use it in GitHub Desktop.
Save dirv/838d6ec201d21af378154357c0e033d7 to your computer and use it in GitHub Desktop.
Svelte testing harness
import { JSDOM } from "jsdom";
import { bind, binding_callbacks } from "svelte/internal";
export const setDomDocument = () => {
const dom = new JSDOM(
"<html><body></body></html>",
{ url: "https://localhost" });
global.document = dom.window.document;
global.window = { ...global.window, ...dom.window };
global.navigator = dom.window.navigator;
global.container = document.createElement("div");
global.document.body.appendChild(global.container);
};
export const click = formElement => {
const evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true);
formElement.dispatchEvent(evt);
return evt;
};
let mountedComponents = [];
export const mountComponent = (component, props = {}, bindings = {}) => {
const mounted = new component({ target: global.container, props });
Object.keys(bindings).forEach(binding => {
binding_callbacks.push(() => {
bind(mounted, binding, value => {
bindings[binding] = value
});
});
});
mountedComponents = [ mounted, ...mountedComponents ];
return mounted;
};
export const unmountAll = () => {
mountedComponents.forEach(component => {
component.$destroy()
});
mountedComponents = [];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment