Skip to content

Instantly share code, notes, and snippets.

@jdhenckel
Last active December 6, 2018 15:20
Show Gist options
  • Save jdhenckel/67c0ef534c3ec92beda5c8c615ed87c7 to your computer and use it in GitHub Desktop.
Save jdhenckel/67c0ef534c3ec92beda5c8c615ed87c7 to your computer and use it in GitHub Desktop.
/*
This can be used in unit tests to simulate a DOM document.
For example, in your jasmine spec file, in the beforeEach, you can do
global.document = new MockElement();
This is not complete. I only implemented the stuff that I needed for my own unit tests.
You should aggressively modify it for your purposes.
*/
export class MockElement {
id = '';
tag = 'HTML';
innerHTML = '';
value = '';
name = '';
disabled = false;
style: any = { display: 'block', backgroundColor: 'red' };
children: MockElement[] = [];
get nextElementSibling() {
return new MockElement();
}
classList = new class {
data: string[] = [];
contains(s: string): boolean {
return this.data.find(a => a == s) != null;
}
add(s: string) {
this.data.push(s);
}
remove(s: string) {
let i = 0;
while ((i = this.data.indexOf(s))>-1) this.data.splice(i,1);
}
}();
constructor(tag = '', id = '') {
this.id = id;
this.tag = tag;
}
createElement(t: string, id = '') {
return new MockElement(t, id);
}
appendChild(x: any) {
this.children.push(x);
return x;
}
clear() {
this.children = [];
}
focus() {
// do nothing
}
querySelector(sel: string) {
// too hard to implement correctly, so just hack something
if (this.children.length==0) this.children.push(new MockElement(sel));
let list = this.getElementsByTagName(sel);
return list.length > 0 ? list[0] : this.children[0];
}
querySelectorAll(sel: string) {
// too hard to implement correctly, so just return all children
return this.children;
}
getElementById(id: string): any {
// if not found, just CREATE one!!
return this.children.find(x => x.id == id) || this.appendChild(this.createElement('', id));
}
// Returns a NodeList containing all elements with the specified class name
getElementsByClassName(classname: string): any[] {
return this.children.filter((x: any) => x.classList.contains(classname));
}
// Returns a NodeList containing all elements with a specified name
getElementsByName(name: string): any[] {
return this.children.filter((x: any) => x.name == name);
}
// Returns a NodeList containing all elements with the specified tag name
getElementsByTagName(tag: string): any[] {
return this.children.filter((x: any) => x.tag == tag.toUpperCase());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment