helpers.mjs (2649B)
1 // Usage note: if you use these more than once in a given file, be sure to 2 // clean up any navigate event listeners, e.g. by using { once: true }, between 3 // tests. 4 5 const TAB_KEY = "\uE004"; 6 7 export function testFocusWasReset(setupFunc, description) { 8 promise_test(async t => { 9 setupFunc(t); 10 11 const button = document.body.appendChild(document.createElement("button")); 12 const button2 = document.body.appendChild(document.createElement("button")); 13 button.tabIndex = 0; 14 button2.tabIndex = 0; 15 t.add_cleanup(() => { 16 button.remove(); 17 button2.remove(); 18 }); 19 20 assert_equals(document.activeElement, document.body, "Start on body"); 21 button.focus(); 22 assert_equals(document.activeElement, button, "focus() worked"); 23 24 const { committed, finished } = navigation.navigate("#" + location.hash.substring(1) + "1"); 25 26 await committed; 27 assert_equals(document.activeElement, button, "Focus stays on the button during the transition"); 28 29 await finished.catch(() => {}); 30 assert_equals(document.activeElement, document.body, "Focus reset after the transition"); 31 32 button2.onfocus = t.unreached_func("button2 must not be focused after pressing Tab"); 33 const focusPromise = waitForFocus(t, button); 34 await test_driver.send_keys(document.body, TAB_KEY); 35 await focusPromise; 36 }, description); 37 } 38 39 export function testFocusWasNotReset(setupFunc, description) { 40 promise_test(async t => { 41 setupFunc(t); 42 43 const button = document.body.appendChild(document.createElement("button")); 44 const button2 = document.body.appendChild(document.createElement("button")); 45 button2.tabIndex = 0; 46 t.add_cleanup(() => { 47 button.remove(); 48 button2.remove(); 49 }); 50 51 assert_equals(document.activeElement, document.body, "Start on body"); 52 button.focus(); 53 assert_equals(document.activeElement, button, "focus() worked"); 54 55 const { committed, finished } = navigation.navigate("#" + location.hash.substring(1) + "1"); 56 57 await committed; 58 assert_equals(document.activeElement, button, "Focus stays on the button during the transition"); 59 60 await finished.catch(() => {}); 61 assert_equals(document.activeElement, button, "Focus stays on the button after the transition"); 62 63 button.onfocus = t.unreached_func("button must not be focused after pressing Tab"); 64 const focusPromise = waitForFocus(t, button2); 65 await test_driver.send_keys(document.body, TAB_KEY); 66 await focusPromise; 67 }, description); 68 } 69 70 function waitForFocus(t, target) { 71 return new Promise(resolve => { 72 target.addEventListener("focus", () => resolve(), { once: true }); 73 }); 74 }