test_wrapped_js_enumerator.js (2007B)
1 "use strict"; 2 3 // Tests that JS iterators are automatically wrapped into 4 // equivalent nsISimpleEnumerator objects. 5 6 const Variant = Components.Constructor("@mozilla.org/variant;1", 7 "nsIWritableVariant", 8 "setFromVariant"); 9 const SupportsInterfacePointer = Components.Constructor( 10 "@mozilla.org/supports-interface-pointer;1", "nsISupportsInterfacePointer"); 11 12 function wrapEnumerator1(iter) { 13 var ip = SupportsInterfacePointer(); 14 ip.data = iter; 15 return ip.data.QueryInterface(Ci.nsISimpleEnumerator); 16 } 17 18 function wrapEnumerator2(iter) { 19 var ip = SupportsInterfacePointer(); 20 ip.data = { 21 QueryInterface: ChromeUtils.generateQI(["nsIFilePicker"]), 22 get files() { 23 return iter; 24 }, 25 }; 26 return ip.data.QueryInterface(Ci.nsIFilePicker).files; 27 } 28 29 30 function enumToArray(iter) { 31 let result = []; 32 while (iter.hasMoreElements()) { 33 result.push(iter.getNext().QueryInterface(Ci.nsIVariant)); 34 } 35 return result; 36 } 37 38 add_task(async function test_wrapped_js_enumerator() { 39 let array = [1, 2, 3, 4]; 40 41 for (let wrapEnumerator of [wrapEnumerator1, wrapEnumerator2]) { 42 // Test a plain JS iterator. This should automatically be wrapped into 43 // an equivalent nsISimpleEnumerator. 44 { 45 let iter = wrapEnumerator(array.values()); 46 let result = enumToArray(iter); 47 48 deepEqual(result, array, "Got correct result"); 49 } 50 51 // Test an object with a QueryInterface method, which implements 52 // nsISimpleEnumerator. This should be wrapped and used directly. 53 { 54 let obj = { 55 QueryInterface: ChromeUtils.generateQI(["nsISimpleEnumerator"]), 56 _idx: 0, 57 hasMoreElements() { 58 return this._idx < array.length; 59 }, 60 getNext() { 61 return Variant(array[this._idx++]); 62 }, 63 }; 64 65 let iter = wrapEnumerator(obj); 66 let result = enumToArray(iter); 67 68 deepEqual(result, array, "Got correct result"); 69 } 70 } 71 });