-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-utils.js
executable file
·60 lines (57 loc) · 1.67 KB
/
test-utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
export class TestUtils {
/**
* Renders a given element with provided attributes
* and returns a promise which resolves as soon as
* rendered element becomes available.
* @param {string} tag
* @param {object} attributes
* @returns {Promise<HTMLElement>}
*/
static render(tag, attributes = {}) {
TestUtils._renderToDocument(tag, attributes);
return TestUtils._waitForComponentToRender(tag);
}
/**
* Replaces document's body with provided element
* including given attributes.
* @param {string} tag
* @param {object} attributes
*/
static _renderToDocument(tag, attributes) {
const htmlAttributes = TestUtils._mapObjectToHTMLAttributes(attributes);
document.body.innerHTML = `<${tag} ${htmlAttributes}></${tag}>`;
}
/**
* Converts an object to HTML string representation of attributes.
*
* For example: `{ foo: "bar", baz: "foo" }`
* becomes `foo="bar" baz="foo"`
*
* @param {object} attributes
* @returns {string}
*/
static _mapObjectToHTMLAttributes(attributes) {
return Object.entries(attributes).reduce((previous, current) => {
return previous + `${current[0]}="${current[1]}"`;
}, "");
}
/**
* Returns a promise which resolves as soon as
* requested element becomes available.
* @param {string} tag
* @returns {Promise<HTMLElement>}
*/
static async _waitForComponentToRender(tag) {
return new Promise(resolve => {
function requestComponent() {
const element = document.querySelector(tag);
if (element) {
resolve(element);
} else {
window.requestAnimationFrame(requestComponent);
}
}
requestComponent();
});
}
}