Skip to content

Instantly share code, notes, and snippets.

@tclancy
Forked from fredyfx/MockElement.ts
Created July 13, 2021 20:17
Show Gist options
  • Save tclancy/eafc082645722fbc69937841cbec702f to your computer and use it in GitHub Desktop.
Save tclancy/eafc082645722fbc69937841cbec702f to your computer and use it in GitHub Desktop.
Mock DOM Document and Element in TypeScript for Unit testing in Headless environment.
/*
This can be used in unit tests to simulate a DOM document.
I have implemented the bare minimum. Feel free to add more, or to change my implementation.
Sample Usage:
import 'jasmine';
import { MockElement } from './support/mock-element';
describe('Utils test', () => {
let doc = new MockElement('HTML');
beforeAll(() => {
utils = new Utils(<any>doc);
});
it('should generate table in DOM', () => {
u.makeTable('table1');
let t = doc.getElementById('table1');
expect(t.children.length).toEqual(5);
});
});
*/
export class MockElement {
id = '';
tag = 'HTML';
innerHTML = '';
value = '';
name = '';
disabled = false;
style = { display: 'block', backgroundColor: 'red' };
children: 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)
}
}();
constructor(tag = '', id = '') {
this.id = id
this.tag = tag
}
createElement(t: string, id = ''): MockElement {
return new MockElement(t, id)
}
appendChild(x: MockElement): MockElement {
this.children.push(x)
return x
}
clear(): void {
this.children = []
}
querySelector(sel: string): MockElement {
// too hard to implement correctly, so just hack something
const list = this.getElementsByTagName(sel)
return list.length > 0 ? list[0] : this.children[0]
}
querySelectorAll(sel: string): MockElement[] {
// too hard to implement correctly, so just return all children
return this.children
}
getElementById(id: string): MockElement {
// if not found, just CREATE one!!
return this.children.find((x) => x.id === id) || this.appendChild(this.createElement('', id))
}
getElementsByClassName(classname: string): MockElement[] {
return this.children.filter((x: MockElement) => x.classList.contains(classname))
}
getElementsByName(name: string): MockElement[] {
return this.children.filter((x: MockElement) => x.name === name)
}
getElementsByTagName(tag: string): MockElement[] {
return this.children.filter((x: MockElement) => x.tag === tag.toUpperCase())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment