utils.js (1918B)
1 // Looks for <template> elements, and runs each test in turn, for example: 2 // 3 // <template data-name="Example test"> 4 // <style> 5 // @function --f() returns <length> { 6 // result: calc(1px + 1px); 7 // } 8 // #target { 9 // --actual: --f(); 10 // --expected: 2px; 11 // } 12 // </style> 13 // </template> 14 // 15 // The test passes if the computed value of --actual matches 16 // the computed value of --expected on #target. 17 // 18 // Elements <div id=target> and <div=main> are assumed to exist. 19 function test_all_templates() { 20 let templates = document.querySelectorAll('template'); 21 for (let template of templates) { 22 test((t) => { 23 t.add_cleanup(() => main.replaceChildren()); 24 main.append(template.content.cloneNode(true)); 25 let cs = getComputedStyle(target); 26 let actual = cs.getPropertyValue('--actual'); 27 let expected = cs.getPropertyValue('--expected'); 28 assert_equals(actual, expected); 29 }, template.getAttribute('data-name')); 30 } 31 } 32 33 // Within an array of elements, find an element with id=target (recursively, 34 // including shadows). 35 function find_target(elements) { 36 for (let e of (elements ?? [])) { 37 let t = e.id == 'target' ? e : null; 38 t ??= find_target(e.children); 39 t ??= find_target(e.shadowRoot?.children); 40 if (t) { 41 return t; 42 } 43 } 44 return null; 45 } 46 47 // Similar to test_all_templates(), but treats each <div data-name="..."> 48 // as a test, and lets ShadowDOM do the "inflation". 49 function test_all_shadows() { 50 let hosts = document.querySelectorAll('div[data-name]'); 51 for (let host of hosts) { 52 test((t) => { 53 let target = find_target([host]); 54 assert_true(target != null); 55 let cs = getComputedStyle(target); 56 let actual = cs.getPropertyValue('--actual'); 57 let expected = cs.getPropertyValue('--expected'); 58 assert_equals(actual, expected); 59 }, host.getAttribute('data-name')); 60 } 61 }