test_defineESModuleGetters.js (2125B)
1 function assertAccessor(lazy, name) { 2 let desc = Object.getOwnPropertyDescriptor(lazy, name); 3 Assert.equal(typeof desc.get, "function"); 4 Assert.equal(desc.get.name, name); 5 Assert.equal(typeof desc.set, "function"); 6 Assert.equal(desc.set.name, name); 7 Assert.equal(desc.enumerable, true); 8 Assert.equal(desc.configurable, true); 9 } 10 11 function assertDataProperty(lazy, name, value) { 12 let desc = Object.getOwnPropertyDescriptor(lazy, name); 13 Assert.equal(desc.value, value); 14 Assert.equal(desc.writable, true); 15 Assert.equal(desc.enumerable, true); 16 Assert.equal(desc.configurable, true); 17 } 18 19 add_task(function test_getter() { 20 // The property should be defined as getter, and getting it should make it 21 // a data property. 22 23 const lazy = {}; 24 ChromeUtils.defineESModuleGetters(lazy, { 25 X: "resource://test/esm_lazy-1.sys.mjs", 26 }); 27 28 assertAccessor(lazy, "X"); 29 30 Assert.equal(lazy.X, 10); 31 assertDataProperty(lazy, "X", 10); 32 }); 33 34 add_task(function test_setter() { 35 // Setting the value before the first get should result in a data property. 36 const lazy = {}; 37 ChromeUtils.defineESModuleGetters(lazy, { 38 X: "resource://test/esm_lazy-1.sys.mjs", 39 }); 40 41 assertAccessor(lazy, "X"); 42 lazy.X = 20; 43 Assert.equal(lazy.X, 20); 44 assertDataProperty(lazy, "X", 20); 45 46 // The above set shouldn't affect the module's value. 47 const lazy2 = {}; 48 ChromeUtils.defineESModuleGetters(lazy2, { 49 X: "resource://test/esm_lazy-1.sys.mjs", 50 }); 51 52 Assert.equal(lazy2.X, 10); 53 }); 54 55 add_task(function test_order() { 56 // The change to the exported value should be reflected until it's accessed. 57 58 const lazy = {}; 59 ChromeUtils.defineESModuleGetters(lazy, { 60 Y: "resource://test/esm_lazy-2.sys.mjs", 61 AddY: "resource://test/esm_lazy-2.sys.mjs", 62 }); 63 64 assertAccessor(lazy, "Y"); 65 assertAccessor(lazy, "AddY"); 66 67 // The change before getting the value should be reflected. 68 lazy.AddY(2); 69 Assert.equal(lazy.Y, 22); 70 assertDataProperty(lazy, "Y", 22); 71 72 // Change after getting the value shouldn't be reflected. 73 lazy.AddY(2); 74 Assert.equal(lazy.Y, 22); 75 assertDataProperty(lazy, "Y", 22); 76 });