test_weakRefs.html (3172B)
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>Test WeakRef works in the browser</title> 6 <script src="/tests/SimpleTest/SimpleTest.js"></script> 7 <script type="application/javascript"> 8 let wr1, wr2, wr3, wr4; 9 10 function go() { 11 SimpleTest.waitForExplicitFinish(); 12 13 // 1. WeakRef with JS target. 14 wr1 = new WeakRef({}); 15 16 // 2. WeakRef with DOM object target (without preserved wrapper). 17 wr2 = new WeakRef(document.createElement("div")); 18 19 // 3. WeakRef with DOM object target (with preserved wrapper). 20 let object = document.createElement("div"); 21 object.someProperty = true; 22 wr3 = new WeakRef(object); 23 object = null 24 25 // 4. WeakRef with reachable DOM object target without preserved wrapper. 26 document.body.appendChild(document.createElement("div")); 27 wr4 = new WeakRef(document.body.lastChild); 28 29 // WeakRef should keep the target in the current task. 30 isnot(wr1.deref(), undefined, "deref() should return its target."); 31 isnot(wr2.deref(), undefined, "deref() should return its target."); 32 isnot(wr3.deref(), undefined, "deref() should return its target."); 33 isnot(wr4.deref(), undefined, "deref() should return its target."); 34 35 // WeakRef should keep the target until the end of current task, which 36 // includes promise microtasks. 37 Promise.resolve().then(() => { 38 isnot(wr1.deref(), undefined, "deref() should return its target."); 39 isnot(wr2.deref(), undefined, "deref() should return its target."); 40 isnot(wr3.deref(), undefined, "deref() should return its target."); 41 isnot(wr4.deref(), undefined, "deref() should return its target."); 42 }); 43 44 // setTimeout will call its callback in a new task. 45 setTimeout(task2, 0); 46 } 47 48 function task2() { 49 // Trigger a full GC/CC/GC cycle to collect WeakRef targets. 50 SpecialPowers.DOMWindowUtils.garbageCollect(); 51 SpecialPowers.DOMWindowUtils.cycleCollect(); 52 SpecialPowers.DOMWindowUtils.garbageCollect(); 53 54 is(wr1.deref(), undefined, "deref() should return undefined."); 55 is(wr2.deref(), undefined, "deref() should return undefined."); 56 is(wr3.deref(), undefined, "deref() should return undefined."); 57 isnot(wr4.deref(), undefined, "deref() should return its target."); 58 59 // setTimeout will call its callback in a new task. 60 setTimeout(task3, 0); 61 } 62 63 function task3() { 64 document.body.removeChild(document.body.lastChild); 65 66 SpecialPowers.DOMWindowUtils.garbageCollect(); 67 SpecialPowers.DOMWindowUtils.cycleCollect(); 68 SpecialPowers.DOMWindowUtils.garbageCollect(); 69 70 is(wr1.deref(), undefined, "deref() should return undefined."); 71 is(wr2.deref(), undefined, "deref() should return undefined."); 72 is(wr3.deref(), undefined, "deref() should return undefined."); 73 is(wr4.deref(), undefined, "deref() should return undefined."); 74 75 SimpleTest.finish(); 76 } 77 </script> 78 </head> 79 <body onload="go()"></body> 80 </html>