Map-forEach.js (1741B)
1 /* test Map.prototype.forEach */ 2 3 load(libdir + 'asserts.js'); 4 load(libdir + 'iteration.js'); 5 6 // testing success conditions of Map.prototype.forEach 7 8 var testMap = new Map(); 9 10 function callback(value, key, map) { 11 testMap.set(key, value); 12 assertEq(map.has(key), true); 13 assertEq(map.get(key), value); 14 } 15 16 var initialMap = new Map([['a', 1], ['b', 2.3], [false, undefined]]); 17 initialMap.forEach(callback); 18 19 // test that both the Maps are equal and are in same order 20 var iterator = initialMap[Symbol.iterator](); 21 var count = 0; 22 for (var [k, v] of testMap) { 23 assertEq(initialMap.has(k), true); 24 assertEq(initialMap.get(k), testMap.get(k)); 25 assertIteratorNext(iterator, [k, testMap.get(k)]); 26 count++; 27 } 28 29 //check both the Maps we have are equal in size 30 assertEq(initialMap.size, testMap.size); 31 assertEq(initialMap.size, count); 32 33 var x = { abc: 'test'}; 34 function callback2(value, key, map) { 35 assertEq(x, this); 36 } 37 initialMap = new Map([['a', 1]]); 38 initialMap.forEach(callback2, x); 39 40 // testing failure conditions of Map.prototype.forEach 41 42 var s = new Set([1, 2, 3]); 43 assertThrowsInstanceOf(function() { 44 Map.prototype.forEach.call(s, callback); 45 }, TypeError, "Map.prototype.forEach should raise TypeError if not used on a Map"); 46 47 var fn = 2; 48 assertThrowsInstanceOf(function() { 49 initialMap.forEach(fn); 50 }, TypeError, "Map.prototype.forEach should raise TypeError if callback is not a function"); 51 52 // testing that Map#forEach uses internal next() function. 53 54 var m = new Map([["one", 1]]); 55 Object.getPrototypeOf(m[Symbol.iterator]()).next = function () { throw "FAIL"; }; 56 assertThrowsValue(function () { 57 m.forEach(function () { throw Math; }); 58 }, Math, "Map.prototype.forEach should use intrinsic next method.");