How to use createFunction method in Playwright Internal

Best JavaScript code snippet using playwright-internal

eva.js

Source:eva.js Github

copy

Full Screen

...23 24 describe(".createFunction", function() {25 var createFunction = eva.createFunction;26 27 describe("createFunction(sCode)", function() {28 it("should return function that executes given code", function() {29 var func;30 31 func = createFunction();32 expect( func )33 .a("function");34 expect( func() )35 .equal(undef);36 37 func = createFunction("");38 expect( func )39 .a("function");40 expect( func() )41 .equal(undef);42 43 func = createFunction("return 1;");44 expect( func )45 .a("function");46 expect( func() )47 .equal(1);48 49 func = createFunction("return [].push;");50 expect( func )51 .a("function");52 expect( func() )53 .eql(Array.prototype.push);54 55 func = createFunction("return (arguments[0] || 0) + (arguments[1] || 0);");56 expect( func )57 .a("function");58 expect( func() )59 .equal(0);60 expect( func(123) )61 .equal(123);62 expect( func(1, 2) )63 .equal(3);64 expect( func(10, 1, 5, 8) )65 .equal(11);66 });67 68 it("should return function that throws an exception", function() {69 var func;70 71 func = createFunction("a");72 expect( func )73 .Throw(Error);74 75 func = createFunction("[].________________();");76 expect( func )77 .Throw(Error);78 79 func = createFunction("return argument[0];");80 expect( func )81 .Throw(Error);82 });83 84 it("should throw a SyntaxError exception", function() {85 expect( createFunction.bind(null, "return -;") )86 .Throw(SyntaxError);87 88 expect( createFunction.bind(null, "return ()") )89 .Throw(SyntaxError);90 91 expect( createFunction.bind(null, "{a:'}") )92 .Throw(SyntaxError);93 94 expect( createFunction.bind(null, "function(,a) {}") )95 .Throw(SyntaxError);96 97 expect( createFunction.bind(null, "{:}") )98 .Throw(SyntaxError);99 100 expect( createFunction.bind(null, "[-]") )101 .Throw(SyntaxError);102 103 expect( createFunction.bind(null, "*[]*") )104 .Throw(SyntaxError);105 });106 });107 108 describe("createFunction(sCode, {expression: true})", function() {109 it("should prefix function code with 'return' statement", function() {110 var func;111 112 func = createFunction("Math", {expression: true});113 expect( func )114 .a("function");115 expect( func() )116 .equal(Math);117 118 func = createFunction("new Date", {expression: true});119 expect( func )120 .a("function");121 expect( func() )122 .instanceOf(Date);123 124 func = createFunction("null", {expression: true});125 expect( func )126 .a("function");127 expect( func() )128 .equal(null);129 130 func = createFunction("{}", {expression: true});131 expect( func )132 .a("function");133 expect( func() )134 .eql({});135 136 func = createFunction("{a: 1, b: 2}", {expression: true});137 expect( func )138 .a("function");139 expect( func() )140 .eql({a: 1, b: 2});141 142 func = createFunction("[]", {expression: true});143 expect( func )144 .a("function");145 expect( func() )146 .eql([]);147 148 func = createFunction("['a', 8]", {expression: true});149 expect( func )150 .a("function");151 expect( func() )152 .eql(["a", 8]);153 });154 });155 156 describe("createFunction(sCode, {paramNames: 'a, b, c'})", function() {157 it("should create function that accepts parameters with specified names", function() {158 var func;159 160 func = createFunction("return p;", {paramNames: "p"});161 expect( func )162 .a("function");163 expect( func() )164 .equal(undef);165 expect( func(1) )166 .equal(1);167 expect( func(Object) )168 .equal(Object);169 expect( func(eva) )170 .equal(eva);171 expect( func("p") )172 .equal("p");173 174 func = createFunction("if (typeof abc === 'function') {return 'f';} else {return abc;}", {paramNames: "abc"});175 expect( func )176 .a("function");177 expect( func() )178 .equal(undef);179 expect( func(1) )180 .equal(1);181 expect( func(createFunction) )182 .equal("f");183 expect( func("value") )184 .equal("value");185 expect( func(null) )186 .equal(null);187 188 func = createFunction("(a || 0) + (b || 0) + (c || 0)", {paramNames: "a, b, c", expression: true});189 expect( func )190 .a("function");191 expect( func() )192 .equal(0);193 expect( func(1) )194 .equal(1);195 expect( func(1, 2) )196 .equal(3);197 expect( func(1, 2, 3) )198 .equal(6);199 });200 });201 202 describe("createFunction(sCode, {scope: true})", function() {203 it("should wrap function code using 'with' statement", function() {204 var func;205 206 func = createFunction("return field;", {scope: true});207 expect( func )208 .a("function");209 expect( func({field: "value"}) )210 .equal("value");211 212 func = createFunction("return a + (sc.b || 0);", {scope: true});213 expect( func )214 .a("function");215 expect( func({a: 1}) )216 .equal(1);217 expect( func({a: 1, b: 100}) )218 .equal(101);219 220 func = createFunction("return push;", {scope: true});221 expect( func )222 .a("function");223 expect( func([]) )224 .equal([].push);225 226 func = createFunction("return b.c;", {scope: true});227 expect( func )228 .a("function");229 expect( func({b: {c: "a"}}) )230 .equal("a");231 232 func = createFunction("if (obj.b) {return a + b;} else {return 'a=' + a;}", {scope: true, paramNames: "obj"});233 expect( func )234 .a("function");235 expect( func({a: "beta"}) )236 .equal("a=beta");237 expect( func({a: 3, b: null}) )238 .equal("a=3");239 expect( func({a: 3, b: 1}) )240 .equal(4);241 expect( func({a: "a", b: "bc"}) )242 .equal("abc");243 244 func = createFunction("if (value && value in space) {return space[value];} else {return def;}", {scope: true, paramNames: "space, value"});245 expect( func )246 .a("function");247 expect( func({a: "beta", def: "default"}) )248 .equal("default");249 expect( func({a: 3}, "a") )250 .equal(3);251 expect( func({a: 3, b: 1}, "b") )252 .equal(1);253 expect( func({def: "unknown", a: "a", b: "b"}, "c") )254 .equal("unknown");255 256 func = createFunction("a + (p1 || 0) + (p2 || 0)", {scope: true, paramNames: "obj, p1, p2", expression: true});257 expect( func )258 .a("function");259 expect( func({a: 0}) )260 .equal(0);261 expect( func({a: 1}, 1) )262 .equal(2);263 expect( func({a: "a"}, 1) )264 .equal("a10");265 expect( func({a: 1}, 2, 3) )266 .equal(6);267 expect( func({a: 10}, 20, 3, 40) )268 .equal(33);269 expect( func({a: "a"}, "b", "c", 5) )270 .equal("abc");271 expect( func({a: "a ", p1: "object property "}, "b ", "c ") )272 .equal("a object property c ");273 expect( func({a: "a ", p1: "- b ", p2: "- c"}, "b ", "c ") )274 .equal("a - b - c");275 });276 277 it("should return function that throws an ReferenceError exception", function() {278 var func;279 280 func = createFunction("a", {scope: true});281 expect( func.bind(null, {}) )282 .Throw(ReferenceError);283 284 func = createFunction("return value;", {scope: true, paramNames: "obj"});285 expect( func.bind(null, {a: 1, v: 2}) )286 .Throw(ReferenceError);287 288 func = createFunction("param > a ? a : b", {scope: true, paramNames: "space, a, b", expression: true});289 expect( func.bind(null, {a: 1, prm: 5}) )290 .Throw(ReferenceError);291 });292 });293 294 describe("createFunction(sCode, {debug: true})", function() {295 var consoleLog, logData;296 297 function saveLog() {298 logData = Array.prototype.slice.call(arguments);299 consoleLog.apply(console, arguments);300 }301 302 before(function() {303 consoleLog = console.log;304 console.log = saveLog;305 });306 307 after(function() {308 console.log = consoleLog;309 });310 311 function check(sCode, sMessage) {312 /*jshint expr:true, sub:true*/313 var settings = {debug: true};314 if (sMessage) {315 settings.debugMessage = sMessage;316 }317 expect( createFunction(sCode, settings)() )318 .be["undefined"];319 expect(logData)320 .an("array");321 expect(logData)322 .length(2);323 expect(logData[0])324 .equal(sMessage || "Error in created function:");325 expect(logData[1])326 .instanceOf(Error);327 logData = null;328 }329 330 it("should log data about error into console", function() {331 check("abc.def");332 });333 334 describe("createFunction(sCode, {debug: true, debugMessage: 'Some message'})", function() {335 it("should log data about error into console using specified message at the beginning", function() {336 /*jshint quotmark:false*/337 check("writeSomewhere(-something.really.good);", 'Something "awful" is happened - ');338 });339 });340 });341 342 describe("createFunction(sCode, {debug: true, debugFunc: 'expression'})", function() {343 var errorData;344 345 function saveErrorData() {346 errorData = Array.prototype.slice.call(arguments);347 }348 349 before(function() {350 global.simpleErrorHandler = {351 process: saveErrorData352 };353 });354 355 after(function() {356 delete global.simpleErrorHandler;357 });358 359 function check(sCode, sDebugFunc) {360 /*jshint expr:true, sub:true*/361 var settings = {debug: true, debugFunc: sDebugFunc || "simpleErrorHandler.process"};362 expect( createFunction(sCode, settings)() )363 .be["undefined"];364 expect(errorData)365 .an("array");366 expect(errorData)367 .length(2);368 expect(errorData[0])369 .equal("Error in created function:");370 expect(errorData[1])371 .instanceOf(Error);372 errorData = null;373 }374 375 it("should pass data about error into specified function", function() {376 check("x.y.z()");...

Full Screen

Full Screen

proxies-function.js

Source:proxies-function.js Github

copy

Full Screen

...27// Flags: --harmony-proxies --allow-natives-syntax28// Helper.29function CreateFrozen(handler, callTrap, constructTrap) {30 if (handler.fix === undefined) handler.fix = function() { return {} }31 var f = Proxy.createFunction(handler, callTrap, constructTrap)32 Object.freeze(f)33 return f34}35// Ensures that checking the "length" property of a function proxy doesn't36// crash due to lack of a [[Get]] method.37var handler = {38 get : function(r, n) { return n == "length" ? 2 : undefined }39}40// Calling (call, Function.prototype.call, Function.prototype.apply,41// Function.prototype.bind).42var global_object = this43var receiver44function TestCall(isStrict, callTrap) {45 assertEquals(42, callTrap(5, 37))46 // TODO(rossberg): strict mode seems to be broken on x64...47 // assertSame(isStrict ? undefined : global_object, receiver)48 var handler = {49 get: function(r, k) {50 return k == "length" ? 2 : Function.prototype[k]51 }52 }53 var f = Proxy.createFunction(handler, callTrap)54 var o = {f: f}55 global_object.f = f56 receiver = 33357 assertEquals(42, f(11, 31))58 // TODO(rossberg): strict mode seems to be broken on x64...59 // assertSame(isStrict ? undefined : global_object, receiver)60 receiver = 33361 assertEquals(42, o.f(10, 32))62 assertSame(o, receiver)63 receiver = 33364 assertEquals(42, o["f"](9, 33))65 assertSame(o, receiver)66 receiver = 33367 assertEquals(42, (1, o).f(8, 34))68 assertSame(o, receiver)69 receiver = 33370 assertEquals(42, (1, o)["f"](7, 35))71 assertSame(o, receiver)72 receiver = 33373 assertEquals(42, f.call(o, 32, 10))74 assertSame(o, receiver)75 receiver = 33376 assertEquals(42, f.call(undefined, 33, 9))77 assertSame(isStrict ? undefined : global_object, receiver)78 receiver = 33379 assertEquals(42, f.call(null, 33, 9))80 assertSame(isStrict ? null : global_object, receiver)81 receiver = 33382 assertEquals(44, f.call(2, 21, 23))83 assertSame(2, receiver.valueOf())84 receiver = 33385 assertEquals(42, Function.prototype.call.call(f, o, 20, 22))86 assertSame(o, receiver)87 receiver = 33388 assertEquals(43, Function.prototype.call.call(f, null, 20, 23))89 assertSame(isStrict ? null : global_object, receiver)90 assertEquals(44, Function.prototype.call.call(f, 2, 21, 23))91 assertEquals(2, receiver.valueOf())92 receiver = 33393 assertEquals(32, f.apply(o, [16, 16]))94 assertSame(o, receiver)95 receiver = 33396 assertEquals(32, Function.prototype.apply.call(f, o, [17, 15]))97 assertSame(o, receiver)98 receiver = 33399 assertEquals(42, %Call(o, 11, 31, f))100 assertSame(o, receiver)101 receiver = 333102 assertEquals(42, %Call(null, 11, 31, f))103 assertSame(isStrict ? null : global_object, receiver)104 receiver = 333105 assertEquals(42, %Apply(f, o, [11, 31], 0, 2))106 assertSame(o, receiver)107 receiver = 333108 assertEquals(42, %Apply(f, null, [11, 31], 0, 2))109 assertSame(isStrict ? null : global_object, receiver)110 receiver = 333111 assertEquals(42, %_CallFunction(o, 11, 31, f))112 assertSame(o, receiver)113 receiver = 333114 assertEquals(42, %_CallFunction(null, 11, 31, f))115 assertSame(isStrict ? null : global_object, receiver)116 var ff = Function.prototype.bind.call(f, o, 12)117 assertTrue(ff.length <= 1) // TODO(rossberg): Not spec'ed yet, be lax.118 receiver = 333119 assertEquals(42, ff(30))120 assertSame(o, receiver)121 receiver = 333122 assertEquals(33, Function.prototype.call.call(ff, {}, 21))123 assertSame(o, receiver)124 receiver = 333125 assertEquals(32, Function.prototype.apply.call(ff, {}, [20]))126 assertSame(o, receiver)127 receiver = 333128 assertEquals(23, %Call({}, 11, ff))129 assertSame(o, receiver)130 receiver = 333131 assertEquals(23, %Call({}, 11, 3, ff))132 assertSame(o, receiver)133 receiver = 333134 assertEquals(24, %Apply(ff, {}, [12, 13], 0, 1))135 assertSame(o, receiver)136 receiver = 333137 assertEquals(24, %Apply(ff, {}, [12, 13], 0, 2))138 assertSame(o, receiver)139 receiver = 333140 assertEquals(34, %_CallFunction({}, 22, ff))141 assertSame(o, receiver)142 receiver = 333143 assertEquals(34, %_CallFunction({}, 22, 3, ff))144 assertSame(o, receiver)145 var fff = Function.prototype.bind.call(ff, o, 30)146 assertEquals(0, fff.length)147 receiver = 333148 assertEquals(42, fff())149 assertSame(o, receiver)150 receiver = 333151 assertEquals(42, Function.prototype.call.call(fff, {}))152 assertSame(o, receiver)153 receiver = 333154 assertEquals(42, Function.prototype.apply.call(fff, {}))155 assertSame(o, receiver)156 receiver = 333157 assertEquals(42, %Call({}, fff))158 assertSame(o, receiver)159 receiver = 333160 assertEquals(42, %Call({}, 11, 3, fff))161 assertSame(o, receiver)162 receiver = 333163 assertEquals(42, %Apply(fff, {}, [], 0, 0))164 assertSame(o, receiver)165 receiver = 333166 assertEquals(42, %Apply(fff, {}, [12, 13], 0, 0))167 assertSame(o, receiver)168 receiver = 333169 assertEquals(42, %Apply(fff, {}, [12, 13], 0, 2))170 assertSame(o, receiver)171 receiver = 333172 assertEquals(42, %_CallFunction({}, fff))173 assertSame(o, receiver)174 receiver = 333175 assertEquals(42, %_CallFunction({}, 3, 4, 5, fff))176 assertSame(o, receiver)177 var f = CreateFrozen({}, callTrap)178 receiver = 333179 assertEquals(42, f(11, 31))180 assertSame(isStrict ? undefined : global_object, receiver)181 var o = {f: f}182 receiver = 333183 assertEquals(42, o.f(10, 32))184 assertSame(o, receiver)185 receiver = 333186 assertEquals(42, o["f"](9, 33))187 assertSame(o, receiver)188 receiver = 333189 assertEquals(42, (1, o).f(8, 34))190 assertSame(o, receiver)191 receiver = 333192 assertEquals(42, (1, o)["f"](7, 35))193 assertSame(o, receiver)194 receiver = 333195 assertEquals(42, Function.prototype.call.call(f, o, 20, 22))196 assertSame(o, receiver)197 receiver = 333198 assertEquals(32, Function.prototype.apply.call(f, o, [17, 15]))199 assertSame(o, receiver)200 receiver = 333201 assertEquals(23, %Call(o, 11, 12, f))202 assertSame(o, receiver)203 receiver = 333204 assertEquals(27, %Apply(f, o, [12, 13, 14], 1, 2))205 assertSame(o, receiver)206 receiver = 333207 assertEquals(42, %_CallFunction(o, 18, 24, f))208 assertSame(o, receiver)209}210TestCall(false, function(x, y) {211 receiver = this212 return x + y213})214TestCall(true, function(x, y) {215 "use strict"216 receiver = this217 return x + y218})219TestCall(false, function() {220 receiver = this221 return arguments[0] + arguments[1]222})223TestCall(false, Proxy.createFunction(handler, function(x, y) {224 receiver = this225 return x + y226}))227TestCall(true, Proxy.createFunction(handler, function(x, y) {228 "use strict"229 receiver = this230 return x + y231}))232TestCall(false, CreateFrozen(handler, function(x, y) {233 receiver = this234 return x + y235}))236// Using intrinsics as call traps.237function TestCallIntrinsic(type, callTrap) {238 var f = Proxy.createFunction({}, callTrap)239 var x = f()240 assertTrue(typeof x == type)241}242TestCallIntrinsic("boolean", Boolean)243TestCallIntrinsic("number", Number)244TestCallIntrinsic("string", String)245TestCallIntrinsic("object", Object)246TestCallIntrinsic("function", Function)247// Throwing from call trap.248function TestCallThrow(callTrap) {249 var f = Proxy.createFunction({}, callTrap)250 assertThrows(function(){ f(11) }, "myexn")251 assertThrows(function(){ ({x: f}).x(11) }, "myexn")252 assertThrows(function(){ ({x: f})["x"](11) }, "myexn")253 assertThrows(function(){ Function.prototype.call.call(f, {}, 2) }, "myexn")254 assertThrows(function(){ Function.prototype.apply.call(f, {}, [1]) }, "myexn")255 assertThrows(function(){ %Call({}, f) }, "myexn")256 assertThrows(function(){ %Call({}, 1, 2, f) }, "myexn")257 assertThrows(function(){ %Apply({}, f, [], 3, 0) }, "myexn")258 assertThrows(function(){ %Apply({}, f, [3, 4], 0, 1) }, "myexn")259 assertThrows(function(){ %_CallFunction({}, f) }, "myexn")260 assertThrows(function(){ %_CallFunction({}, 1, 2, f) }, "myexn")261 var f = CreateFrozen({}, callTrap)262 assertThrows(function(){ f(11) }, "myexn")263 assertThrows(function(){ ({x: f}).x(11) }, "myexn")264 assertThrows(function(){ ({x: f})["x"](11) }, "myexn")265 assertThrows(function(){ Function.prototype.call.call(f, {}, 2) }, "myexn")266 assertThrows(function(){ Function.prototype.apply.call(f, {}, [1]) }, "myexn")267 assertThrows(function(){ %Call({}, f) }, "myexn")268 assertThrows(function(){ %Call({}, 1, 2, f) }, "myexn")269 assertThrows(function(){ %Apply({}, f, [], 3, 0) }, "myexn")270 assertThrows(function(){ %Apply({}, f, [3, 4], 0, 1) }, "myexn")271 assertThrows(function(){ %_CallFunction({}, f) }, "myexn")272 assertThrows(function(){ %_CallFunction({}, 1, 2, f) }, "myexn")273}274TestCallThrow(function() { throw "myexn" })275TestCallThrow(Proxy.createFunction({}, function() { throw "myexn" }))276TestCallThrow(CreateFrozen({}, function() { throw "myexn" }))277// Construction (new).278var prototype = {myprop: 0}279var receiver280var handlerWithPrototype = {281 fix: function() { return { prototype: { value: prototype } }; },282 get: function(r, n) {283 if (n == "length") return 2;284 assertEquals("prototype", n);285 return prototype;286 }287}288var handlerSansPrototype = {289 fix: function() { return { length: { value: 2 } } },290 get: function(r, n) {291 if (n == "length") return 2;292 assertEquals("prototype", n);293 return undefined;294 }295}296function ReturnUndef(x, y) {297 "use strict";298 receiver = this;299 this.sum = x + y;300}301function ReturnThis(x, y) {302 "use strict";303 receiver = this;304 this.sum = x + y;305 return this;306}307function ReturnNew(x, y) {308 "use strict";309 receiver = this;310 return {sum: x + y};311}312function ReturnNewWithProto(x, y) {313 "use strict";314 receiver = this;315 var result = Object.create(prototype);316 result.sum = x + y;317 return result;318}319function TestConstruct(proto, constructTrap) {320 TestConstruct2(proto, constructTrap, handlerWithPrototype)321 TestConstruct2(proto, constructTrap, handlerSansPrototype)322}323function TestConstruct2(proto, constructTrap, handler) {324 var f = Proxy.createFunction(handler, function() {}, constructTrap)325 var o = new f(11, 31)326 assertEquals(undefined, receiver)327 assertEquals(42, o.sum)328 assertSame(proto, Object.getPrototypeOf(o))329 var f = CreateFrozen(handler, function() {}, constructTrap)330 var o = new f(11, 32)331 assertEquals(undefined, receiver)332 assertEquals(43, o.sum)333 assertSame(proto, Object.getPrototypeOf(o))334}335TestConstruct(Object.prototype, ReturnNew)336TestConstruct(prototype, ReturnNewWithProto)337TestConstruct(Object.prototype, Proxy.createFunction(handler, ReturnNew))338TestConstruct(prototype, Proxy.createFunction(handler, ReturnNewWithProto))339TestConstruct(Object.prototype, CreateFrozen(handler, ReturnNew))340TestConstruct(prototype, CreateFrozen(handler, ReturnNewWithProto))341// Construction with derived construct trap.342function TestConstructFromCall(proto, returnsThis, callTrap) {343 TestConstructFromCall2(prototype, returnsThis, callTrap, handlerWithPrototype)344 TestConstructFromCall2(proto, returnsThis, callTrap, handlerSansPrototype)345}346function TestConstructFromCall2(proto, returnsThis, callTrap, handler) {347 // TODO(rossberg): handling of prototype for derived construct trap will be348 // fixed in a separate change. Commenting out checks below for now.349 var f = Proxy.createFunction(handler, callTrap)350 var o = new f(11, 31)351 if (returnsThis) assertEquals(o, receiver)352 assertEquals(42, o.sum)353 // assertSame(proto, Object.getPrototypeOf(o))354 var g = CreateFrozen(handler, callTrap)355 // assertSame(f.prototype, g.prototype)356 var o = new g(11, 32)357 if (returnsThis) assertEquals(o, receiver)358 assertEquals(43, o.sum)359 // assertSame(proto, Object.getPrototypeOf(o))360}361TestConstructFromCall(Object.prototype, true, ReturnUndef)362TestConstructFromCall(Object.prototype, true, ReturnThis)363TestConstructFromCall(Object.prototype, false, ReturnNew)364TestConstructFromCall(prototype, false, ReturnNewWithProto)365TestConstructFromCall(Object.prototype, true,366 Proxy.createFunction(handler, ReturnUndef))367TestConstructFromCall(Object.prototype, true,368 Proxy.createFunction(handler, ReturnThis))369TestConstructFromCall(Object.prototype, false,370 Proxy.createFunction(handler, ReturnNew))371TestConstructFromCall(prototype, false,372 Proxy.createFunction(handler, ReturnNewWithProto))373TestConstructFromCall(Object.prototype, true, CreateFrozen({}, ReturnUndef))374TestConstructFromCall(Object.prototype, true, CreateFrozen({}, ReturnThis))375TestConstructFromCall(Object.prototype, false, CreateFrozen({}, ReturnNew))376TestConstructFromCall(prototype, false, CreateFrozen({}, ReturnNewWithProto))377ReturnUndef.prototype = prototype378ReturnThis.prototype = prototype379ReturnNew.prototype = prototype380ReturnNewWithProto.prototype = prototype381TestConstructFromCall(prototype, true, ReturnUndef)382TestConstructFromCall(prototype, true, ReturnThis)383TestConstructFromCall(Object.prototype, false, ReturnNew)384TestConstructFromCall(prototype, false, ReturnNewWithProto)385TestConstructFromCall(Object.prototype, true,386 Proxy.createFunction(handler, ReturnUndef))387TestConstructFromCall(Object.prototype, true,388 Proxy.createFunction(handler, ReturnThis))389TestConstructFromCall(Object.prototype, false,390 Proxy.createFunction(handler, ReturnNew))391TestConstructFromCall(prototype, false,392 Proxy.createFunction(handler, ReturnNewWithProto))393TestConstructFromCall(prototype, true,394 Proxy.createFunction(handlerWithPrototype, ReturnUndef))395TestConstructFromCall(prototype, true,396 Proxy.createFunction(handlerWithPrototype, ReturnThis))397TestConstructFromCall(Object.prototype, false,398 Proxy.createFunction(handlerWithPrototype, ReturnNew))399TestConstructFromCall(prototype, false,400 Proxy.createFunction(handlerWithPrototype,401 ReturnNewWithProto))402TestConstructFromCall(prototype, true,403 CreateFrozen(handlerWithPrototype, ReturnUndef))404TestConstructFromCall(prototype, true,405 CreateFrozen(handlerWithPrototype, ReturnThis))406TestConstructFromCall(Object.prototype, false,407 CreateFrozen(handlerWithPrototype, ReturnNew))408TestConstructFromCall(prototype, false,409 CreateFrozen(handlerWithPrototype, ReturnNewWithProto))410// Throwing from the construct trap.411function TestConstructThrow(trap) {412 TestConstructThrow2(Proxy.createFunction({ fix: function() {return {};} },413 trap))414 TestConstructThrow2(Proxy.createFunction({ fix: function() {return {};} },415 function() {},416 trap))417}418function TestConstructThrow2(f) {419 assertThrows(function(){ new f(11) }, "myexn")420 Object.freeze(f)421 assertThrows(function(){ new f(11) }, "myexn")422}423TestConstructThrow(function() { throw "myexn" })424TestConstructThrow(Proxy.createFunction({}, function() { throw "myexn" }))425TestConstructThrow(CreateFrozen({}, function() { throw "myexn" }))426// Using function proxies as getters and setters.427var value428var receiver429function TestAccessorCall(getterCallTrap, setterCallTrap) {430 var handler = { fix: function() { return {} } }431 var pgetter = Proxy.createFunction(handler, getterCallTrap)432 var psetter = Proxy.createFunction(handler, setterCallTrap)433 var o = {}434 var oo = Object.create(o)435 Object.defineProperty(o, "a", {get: pgetter, set: psetter})436 Object.defineProperty(o, "b", {get: pgetter})437 Object.defineProperty(o, "c", {set: psetter})438 Object.defineProperty(o, "3", {get: pgetter, set: psetter})439 Object.defineProperty(oo, "a", {value: 43})440 receiver = ""441 assertEquals(42, o.a)442 assertSame(o, receiver)443 receiver = ""444 assertEquals(42, o.b)445 assertSame(o, receiver)446 receiver = ""447 assertEquals(undefined, o.c)448 assertEquals("", receiver)449 receiver = ""450 assertEquals(42, o["a"])451 assertSame(o, receiver)452 receiver = ""453 assertEquals(42, o[3])454 assertSame(o, receiver)455 receiver = ""456 assertEquals(43, oo.a)457 assertEquals("", receiver)458 receiver = ""459 assertEquals(42, oo.b)460 assertSame(oo, receiver)461 receiver = ""462 assertEquals(undefined, oo.c)463 assertEquals("", receiver)464 receiver = ""465 assertEquals(43, oo["a"])466 assertEquals("", receiver)467 receiver = ""468 assertEquals(42, oo[3])469 assertSame(oo, receiver)470 receiver = ""471 assertEquals(50, o.a = 50)472 assertSame(o, receiver)473 assertEquals(50, value)474 receiver = ""475 assertEquals(51, o.b = 51)476 assertEquals("", receiver)477 assertEquals(50, value) // no setter478 assertThrows(function() { "use strict"; o.b = 51 }, TypeError)479 receiver = ""480 assertEquals(52, o.c = 52)481 assertSame(o, receiver)482 assertEquals(52, value)483 receiver = ""484 assertEquals(53, o["a"] = 53)485 assertSame(o, receiver)486 assertEquals(53, value)487 receiver = ""488 assertEquals(54, o[3] = 54)489 assertSame(o, receiver)490 assertEquals(54, value)491 value = 0492 receiver = ""493 assertEquals(60, oo.a = 60)494 assertEquals("", receiver)495 assertEquals(0, value) // oo has own 'a'496 assertEquals(61, oo.b = 61)497 assertSame("", receiver)498 assertEquals(0, value) // no setter499 assertThrows(function() { "use strict"; oo.b = 61 }, TypeError)500 receiver = ""501 assertEquals(62, oo.c = 62)502 assertSame(oo, receiver)503 assertEquals(62, value)504 receiver = ""505 assertEquals(63, oo["c"] = 63)506 assertSame(oo, receiver)507 assertEquals(63, value)508 receiver = ""509 assertEquals(64, oo[3] = 64)510 assertSame(oo, receiver)511 assertEquals(64, value)512}513TestAccessorCall(514 function() { receiver = this; return 42 },515 function(x) { receiver = this; value = x }516)517TestAccessorCall(518 function() { "use strict"; receiver = this; return 42 },519 function(x) { "use strict"; receiver = this; value = x }520)521TestAccessorCall(522 Proxy.createFunction({}, function() { receiver = this; return 42 }),523 Proxy.createFunction({}, function(x) { receiver = this; value = x })524)525TestAccessorCall(526 CreateFrozen({}, function() { receiver = this; return 42 }),527 CreateFrozen({}, function(x) { receiver = this; value = x })528)529// Passing a proxy function to higher-order library functions.530function TestHigherOrder(f) {531 assertEquals(6, [6, 2].map(f)[0])532 assertEquals(4, [5, 2].reduce(f, 4))533 assertTrue([1, 2].some(f))534 assertEquals("a.b.c", "a.b.c".replace(".", f))535}536TestHigherOrder(function(x) { return x })537TestHigherOrder(function(x) { "use strict"; return x })538TestHigherOrder(Proxy.createFunction({}, function(x) { return x }))539TestHigherOrder(CreateFrozen({}, function(x) { return x }))540// TODO(rossberg): Ultimately, I want to have the following test function541// run through, but it currently fails on so many cases (some not even542// involving proxies), that I leave that for later...543/*544function TestCalls() {545 var handler = {546 get: function(r, k) {547 return k == "length" ? 2 : Function.prototype[k]548 }549 }550 var bind = Function.prototype.bind551 var o = {}552 var traps = [553 function(x, y) {554 return {receiver: this, result: x + y, strict: false}555 },556 function(x, y) { "use strict";557 return {receiver: this, result: x + y, strict: true}558 },559 function() {560 var x = arguments[0], y = arguments[1]561 return {receiver: this, result: x + y, strict: false}562 },563 Proxy.createFunction(handler, function(x, y) {564 return {receiver: this, result: x + y, strict: false}565 }),566 Proxy.createFunction(handler, function() {567 var x = arguments[0], y = arguments[1]568 return {receiver: this, result: x + y, strict: false}569 }),570 Proxy.createFunction(handler, function(x, y) { "use strict"571 return {receiver: this, result: x + y, strict: true}572 }),573 CreateFrozen(handler, function(x, y) {574 return {receiver: this, result: x + y, strict: false}575 }),576 CreateFrozen(handler, function(x, y) { "use strict"577 return {receiver: this, result: x + y, strict: true}578 }),579 ]580 var creates = [581 function(trap) { return trap },582 function(trap) { return CreateFrozen({}, callTrap) },583 function(trap) { return Proxy.createFunction(handler, callTrap) },584 function(trap) {585 return Proxy.createFunction(handler, CreateFrozen({}, callTrap))586 },587 function(trap) {588 return Proxy.createFunction(handler, Proxy.createFunction(handler, callTrap))589 },590 ]591 var binds = [592 function(f, o, x, y) { return f },593 function(f, o, x, y) { return bind.call(f, o) },594 function(f, o, x, y) { return bind.call(f, o, x) },595 function(f, o, x, y) { return bind.call(f, o, x, y) },596 function(f, o, x, y) { return bind.call(f, o, x, y, 5) },597 function(f, o, x, y) { return bind.call(bind.call(f, o), {}, x, y) },598 function(f, o, x, y) { return bind.call(bind.call(f, o, x), {}, y) },599 function(f, o, x, y) { return bind.call(bind.call(f, o, x, y), {}, 5) },600 ]601 var calls = [602 function(f, x, y) { return f(x, y) },...

Full Screen

Full Screen

function.test.js

Source:function.test.js Github

copy

Full Screen

2const test = require('mapbox-gl-js-test').test;3const createFunction = require('../../../src/style-spec/function');4test('constant function', (t) => {5 t.test('number', (t) => {6 const f = createFunction(1, {type: 'number'});7 t.equal(f(0), 1);8 t.equal(f(1), 1);9 t.equal(f(2), 1);10 t.end();11 });12 t.test('string', (t) => {13 const f = createFunction('mapbox', {type: 'string'});14 t.equal(f(0), 'mapbox');15 t.equal(f(1), 'mapbox');16 t.equal(f(2), 'mapbox');17 t.end();18 });19 t.test('color', (t) => {20 const f = createFunction('red', {type: 'color'});21 t.deepEqual(f(0), [1, 0, 0, 1]);22 t.deepEqual(f(1), [1, 0, 0, 1]);23 t.deepEqual(f(2), [1, 0, 0, 1]);24 t.end();25 });26 t.test('array', (t) => {27 const f = createFunction([1], {type: 'array'});28 t.deepEqual(f(0), [1]);29 t.deepEqual(f(1), [1]);30 t.deepEqual(f(2), [1]);31 t.end();32 });33 t.end();34});35test('exponential function', (t) => {36 t.test('is the default for interpolated properties', (t) => {37 const f = createFunction({38 stops: [[1, 2], [3, 6]],39 base: 240 }, {41 type: 'number',42 function: 'interpolated'43 });44 t.equal(f(2), 30 / 9);45 t.end();46 });47 t.test('base', (t) => {48 const f = createFunction({49 type: 'exponential',50 stops: [[1, 2], [3, 6]],51 base: 252 }, {53 type: 'number'54 });55 t.equal(f(0), 2);56 t.equal(f(1), 2);57 t.equal(f(2), 30 / 9);58 t.equal(f(3), 6);59 t.equal(f(4), 6);60 t.end();61 });62 t.test('one stop', (t) => {63 const f = createFunction({64 type: 'exponential',65 stops: [[1, 2]]66 }, {67 type: 'number'68 });69 t.equal(f(0), 2);70 t.equal(f(1), 2);71 t.equal(f(2), 2);72 t.end();73 });74 t.test('two stops', (t) => {75 const f = createFunction({76 type: 'exponential',77 stops: [[1, 2], [3, 6]]78 }, {79 type: 'number'80 });81 t.equal(f(0), 2);82 t.equal(f(1), 2);83 t.equal(f(2), 4);84 t.equal(f(3), 6);85 t.equal(f(4), 6);86 t.end();87 });88 t.test('three stops', (t) => {89 const f = createFunction({90 type: 'exponential',91 stops: [[1, 2], [3, 6], [5, 10]]92 }, {93 type: 'number'94 });95 t.equal(f(0), 2);96 t.equal(f(1), 2);97 t.equal(f(2), 4);98 t.equal(f(2.5), 5);99 t.equal(f(3), 6);100 t.equal(f(4), 8);101 t.equal(f(4.5), 9);102 t.equal(f(5), 10);103 t.equal(f(6), 10);104 t.end();105 });106 t.test('four stops', (t) => {107 const f = createFunction({108 type: 'exponential',109 stops: [[1, 2], [3, 6], [5, 10], [7, 14]]110 }, {111 type: 'number'112 });113 t.equal(f(0), 2);114 t.equal(f(1), 2);115 t.equal(f(2), 4);116 t.equal(f(2.5), 5);117 t.equal(f(3), 6);118 t.equal(f(3.5), 7);119 t.equal(f(4), 8);120 t.equal(f(4.5), 9);121 t.equal(f(5), 10);122 t.equal(f(6), 12);123 t.equal(f(6.5), 13);124 t.equal(f(7), 14);125 t.equal(f(8), 14);126 t.end();127 });128 t.test('many stops', (t) => {129 const stops = [130 [2, 100],131 [55, 200],132 [132, 300],133 [607, 400],134 [1287, 500],135 [1985, 600],136 [2650, 700],137 [3299, 800],138 [3995, 900],139 [4927, 1000],140 [7147, 10000], // 10141 [10028, 100000], // 11142 [12889, 1000000],143 [40000, 10000000]144 ];145 const f = createFunction({146 type: 'exponential',147 stops: stops148 }, {149 type: 'number'150 });151 t.equal(f(2), 100);152 t.equal(f(20), 133.9622641509434);153 t.equal(f(607), 400);154 t.equal(f(680), 410.7352941176471);155 t.equal(f(4927), 1000); //86156 t.equal(f(7300), 14779.590419993057);157 t.equal(f(10000), 99125.30371398819);158 t.equal(f(20000), 3360628.527166095);159 t.equal(f(40000), 10000000);160 t.end();161 });162 t.test('color', (t) => {163 const f = createFunction({164 type: 'exponential',165 stops: [[1, 'red'], [11, 'blue']]166 }, {167 type: 'color'168 });169 t.deepEqual(f(0), [1, 0, 0, 1]);170 t.deepEqual(f(5), [0.6, 0, 0.4, 1]);171 t.deepEqual(f(11), [0, 0, 1, 1]);172 t.end();173 });174 t.test('lab colorspace', (t) => {175 const f = createFunction({176 type: 'exponential',177 colorSpace: 'lab',178 stops: [[1, [0, 0, 0, 1]], [10, [0, 1, 1, 1]]]179 }, {180 type: 'color'181 });182 t.deepEqual(f(0), [0, 0, 0, 1]);183 t.deepEqual(f(5).map((n) => {184 return parseFloat(n.toFixed(3));185 }), [0, 0.444, 0.444, 1]);186 t.end();187 });188 t.test('rgb colorspace', (t) => {189 const f = createFunction({190 type: 'exponential',191 colorSpace: 'rgb',192 stops: [[0, [0, 0, 0, 1]], [10, [1, 1, 1, 1]]]193 }, {194 type: 'color'195 });196 t.deepEqual(f(5).map((n) => {197 return parseFloat(n.toFixed(3));198 }), [0.5, 0.5, 0.5, 1]);199 t.end();200 });201 t.test('unknown color spaces', (t) => {202 t.throws(() => {203 createFunction({204 type: 'exponential',205 colorSpace: 'unknown',206 stops: [[1, [0, 0, 0, 1]], [10, [0, 1, 1, 1]]]207 }, {208 type: 'color'209 });210 }, 'Unknown color space: unknown');211 t.end();212 });213 t.test('interpolation mutation avoidance', (t) => {214 const params = {215 type: 'exponential',216 colorSpace: 'lab',217 stops: [[1, [0, 0, 0, 1]], [10, [0, 1, 1, 1]]]218 };219 const paramsCopy = JSON.parse(JSON.stringify(params));220 createFunction(params, {221 type: 'color'222 });223 t.deepEqual(params, paramsCopy);224 t.end();225 });226 t.test('property present', (t) => {227 const f = createFunction({228 property: 'foo',229 type: 'exponential',230 stops: [[0, 0], [1, 2]]231 }, {232 type: 'number'233 });234 t.equal(f(0, {foo: 1}), 2);235 t.end();236 });237 t.test('property absent, function default', (t) => {238 const f = createFunction({239 property: 'foo',240 type: 'exponential',241 stops: [[0, 0], [1, 2]],242 default: 3243 }, {244 type: 'number'245 });246 t.equal(f(0, {}), 3);247 t.end();248 });249 t.test('property absent, spec default', (t) => {250 const f = createFunction({251 property: 'foo',252 type: 'exponential',253 stops: [[0, 0], [1, 2]]254 }, {255 type: 'number',256 default: 3257 });258 t.equal(f(0, {}), 3);259 t.end();260 });261 t.test('property type mismatch, function default', (t) => {262 const f = createFunction({263 property: 'foo',264 type: 'exponential',265 stops: [[0, 0], [1, 2]],266 default: 3267 }, {268 type: 'string'269 });270 t.equal(f(0, {foo: 'string'}), 3);271 t.end();272 });273 t.test('property type mismatch, spec default', (t) => {274 const f = createFunction({275 property: 'foo',276 type: 'exponential',277 stops: [[0, 0], [1, 2]]278 }, {279 type: 'string',280 default: 3281 });282 t.equal(f(0, {foo: 'string'}), 3);283 t.end();284 });285 t.test('zoom-and-property function, one stop', (t) => {286 const f = createFunction({287 type: 'exponential',288 property: 'prop',289 stops: [[{ zoom: 1, value: 1 }, 2]]290 }, {291 type: 'number'292 });293 t.equal(f(0, { prop: 0 }), 2);294 t.equal(f(1, { prop: 0 }), 2);295 t.equal(f(2, { prop: 0 }), 2);296 t.equal(f(0, { prop: 1 }), 2);297 t.equal(f(1, { prop: 1 }), 2);298 t.equal(f(2, { prop: 1 }), 2);299 t.equal(f(0, { prop: 2 }), 2);300 t.equal(f(1, { prop: 2 }), 2);301 t.equal(f(2, { prop: 2 }), 2);302 t.end();303 });304 t.test('zoom-and-property function, two stops', (t) => {305 const f = createFunction({306 type: 'exponential',307 property: 'prop',308 base: 1,309 stops: [310 [{ zoom: 1, value: 0 }, 0],311 [{ zoom: 1, value: 2 }, 4],312 [{ zoom: 3, value: 0 }, 0],313 [{ zoom: 3, value: 2 }, 12]]314 }, {315 type: 'number'316 });317 t.equal(f(0, { prop: 1 }), 2);318 t.equal(f(1, { prop: 1 }), 2);319 t.equal(f(2, { prop: 1 }), 4);320 t.equal(f(3, { prop: 1 }), 6);321 t.equal(f(4, { prop: 1 }), 6);322 t.equal(f(2, { prop: -1}), 0);323 t.equal(f(2, { prop: 0}), 0);324 t.equal(f(2, { prop: 2}), 8);325 t.equal(f(2, { prop: 3}), 8);326 t.end();327 });328 t.test('zoom-and-property function, three stops', (t) => {329 const f = createFunction({330 type: 'exponential',331 property: 'prop',332 base: 1,333 stops: [334 [{ zoom: 1, value: 0}, 0],335 [{ zoom: 1, value: 2}, 4],336 [{ zoom: 3, value: 0}, 0],337 [{ zoom: 3, value: 2}, 12],338 [{ zoom: 5, value: 0}, 0],339 [{ zoom: 5, value: 2}, 20]]340 }, {341 type: 'number'342 });343 t.equal(f(0, { prop: 1 }), 2);344 t.equal(f(1, { prop: 1 }), 2);345 t.equal(f(2, { prop: 1 }), 4);346 t.end();347 });348 t.test('zoom-and-property function, two stops, fractional zoom', (t) => {349 const f = createFunction({350 type: 'exponential',351 property: 'prop',352 base: 1,353 stops: [354 [{ zoom: 1.9, value: 0 }, 4],355 [{ zoom: 2.1, value: 0 }, 8]356 ]357 }, {358 type: 'number'359 });360 t.equal(f(1.9, { prop: 1 }), 4);361 t.equal(f(2, { prop: 1 }), 6);362 t.equal(f(2.1, { prop: 1 }), 8);363 t.end();364 });365 t.test('zoom-and-property function, no default', (t) => {366 // This can happen for fill-outline-color, where the spec has no default.367 const f = createFunction({368 type: 'exponential',369 property: 'prop',370 base: 1,371 stops: [372 [{ zoom: 0, value: 1 }, 'red'],373 [{ zoom: 1, value: 1 }, 'red']374 ]375 }, {376 type: 'color'377 });378 t.equal(f(0, {}), undefined);379 t.equal(f(0.5, {}), undefined);380 t.equal(f(1, {}), undefined);381 t.end();382 });383 t.end();384});385test('interval function', (t) => {386 t.test('is the default for piecewise-constant properties', (t) => {387 const f = createFunction({388 stops: [[-1, 11], [0, 111]]389 }, {390 type: 'number',391 function: 'piecewise-constant'392 });393 t.equal(f(-1.5), 11);394 t.equal(f(-0.5), 11);395 t.equal(f(0), 111);396 t.equal(f(0.5), 111);397 t.end();398 });399 t.test('one stop', (t) => {400 const f = createFunction({401 type: 'interval',402 stops: [[0, 11]]403 }, {404 type: 'number'405 });406 t.equal(f(-0.5), 11);407 t.equal(f(0), 11);408 t.equal(f(0.5), 11);409 t.end();410 });411 t.test('two stops', (t) => {412 const f = createFunction({413 type: 'interval',414 stops: [[-1, 11], [0, 111]]415 }, {416 type: 'number'417 });418 t.equal(f(-1.5), 11);419 t.equal(f(-0.5), 11);420 t.equal(f(0), 111);421 t.equal(f(0.5), 111);422 t.end();423 });424 t.test('three stops', (t) => {425 const f = createFunction({426 type: 'interval',427 stops: [[-1, 11], [0, 111], [1, 1111]]428 }, {429 type: 'number'430 });431 t.equal(f(-1.5), 11);432 t.equal(f(-0.5), 11);433 t.equal(f(0), 111);434 t.equal(f(0.5), 111);435 t.equal(f(1), 1111);436 t.equal(f(1.5), 1111);437 t.end();438 });439 t.test('four stops', (t) => {440 const f = createFunction({441 type: 'interval',442 stops: [[-1, 11], [0, 111], [1, 1111], [2, 11111]]443 }, {444 type: 'number'445 });446 t.equal(f(-1.5), 11);447 t.equal(f(-0.5), 11);448 t.equal(f(0), 111);449 t.equal(f(0.5), 111);450 t.equal(f(1), 1111);451 t.equal(f(1.5), 1111);452 t.equal(f(2), 11111);453 t.equal(f(2.5), 11111);454 t.end();455 });456 t.test('color', (t) => {457 const f = createFunction({458 type: 'interval',459 stops: [[1, 'red'], [11, 'blue']]460 }, {461 type: 'color'462 });463 t.deepEqual(f(0), [1, 0, 0, 1]);464 t.deepEqual(f(0), [1, 0, 0, 1]);465 t.deepEqual(f(11), [0, 0, 1, 1]);466 t.end();467 });468 t.test('property present', (t) => {469 const f = createFunction({470 property: 'foo',471 type: 'interval',472 stops: [[0, 'bad'], [1, 'good'], [2, 'bad']]473 }, {474 type: 'string'475 });476 t.equal(f(0, {foo: 1.5}), 'good');477 t.end();478 });479 t.test('property absent, function default', (t) => {480 const f = createFunction({481 property: 'foo',482 type: 'interval',483 stops: [[0, 'zero'], [1, 'one'], [2, 'two']],484 default: 'default'485 }, {486 type: 'string'487 });488 t.equal(f(0, {}), 'default');489 t.end();490 });491 t.test('property absent, spec default', (t) => {492 const f = createFunction({493 property: 'foo',494 type: 'interval',495 stops: [[0, 'zero'], [1, 'one'], [2, 'two']]496 }, {497 type: 'string',498 default: 'default'499 });500 t.equal(f(0, {}), 'default');501 t.end();502 });503 t.test('property type mismatch, function default', (t) => {504 const f = createFunction({505 property: 'foo',506 type: 'interval',507 stops: [[0, 'zero'], [1, 'one'], [2, 'two']],508 default: 'default'509 }, {510 type: 'string'511 });512 t.equal(f(0, {foo: 'string'}), 'default');513 t.end();514 });515 t.test('property type mismatch, spec default', (t) => {516 const f = createFunction({517 property: 'foo',518 type: 'interval',519 stops: [[0, 'zero'], [1, 'one'], [2, 'two']]520 }, {521 type: 'string',522 default: 'default'523 });524 t.equal(f(0, {foo: 'string'}), 'default');525 t.end();526 });527 t.end();528});529test('categorical function', (t) => {530 t.test('string', (t) => {531 const f = createFunction({532 property: 'foo',533 type: 'categorical',534 stops: [[0, 'bad'], [1, 'good'], [2, 'bad']]535 }, {536 type: 'string'537 });538 t.equal(f(0, {foo: 0}), 'bad');539 t.equal(f(0, {foo: 1}), 'good');540 t.equal(f(0, {foo: 2}), 'bad');541 t.end();542 });543 t.test('string function default', (t) => {544 const f = createFunction({545 property: 'foo',546 type: 'categorical',547 stops: [[0, 'zero'], [1, 'one'], [2, 'two']],548 default: 'default'549 }, {550 type: 'string'551 });552 t.equal(f(0, {}), 'default');553 t.equal(f(0, {foo: 3}), 'default');554 t.end();555 });556 t.test('strict type checking', (t) => {557 const numberKeys = createFunction({558 property: 'foo',559 type: 'categorical',560 stops: [[0, 'zero'], [1, 'one'], [2, 'two']],561 default: 'default'562 }, {563 type: 'string'564 });565 const stringKeys = createFunction({566 property: 'foo',567 type: 'categorical',568 stops: [['0', 'zero'], ['1', 'one'], ['2', 'two'], ['true', 'yes'], ['false', 'no']],569 default: 'default'570 }, {571 type: 'string'572 });573 t.equal(numberKeys(0, {foo: '0'}), 'default');574 t.equal(numberKeys(0, {foo: '1'}), 'default');575 t.equal(numberKeys(0, {foo: false}), 'default');576 t.equal(numberKeys(0, {foo: true}), 'default');577 t.equal(stringKeys(0, {foo: 0}), 'default');578 t.equal(stringKeys(0, {foo: 1}), 'default');579 t.equal(stringKeys(0, {foo: false}), 'default');580 t.equal(stringKeys(0, {foo: true}), 'default');581 t.end();582 });583 t.test('string spec default', (t) => {584 const f = createFunction({585 property: 'foo',586 type: 'categorical',587 stops: [[0, 'zero'], [1, 'one'], [2, 'two']]588 }, {589 type: 'string',590 default: 'default'591 });592 t.equal(f(0, {}), 'default');593 t.equal(f(0, {foo: 3}), 'default');594 t.end();595 });596 t.test('color', (t) => {597 const f = createFunction({598 property: 'foo',599 type: 'categorical',600 stops: [[0, 'red'], [1, 'blue']]601 }, {602 type: 'color'603 });604 t.deepEqual(f(0, {foo: 0}), [1, 0, 0, 1]);605 t.deepEqual(f(1, {foo: 1}), [0, 0, 1, 1]);606 t.end();607 });608 t.test('color function default', (t) => {609 const f = createFunction({610 property: 'foo',611 type: 'categorical',612 stops: [[0, 'red'], [1, 'blue']],613 default: 'lime'614 }, {615 type: 'color'616 });617 t.deepEqual(f(0, {}), [0, 1, 0, 1]);618 t.deepEqual(f(0, {foo: 3}), [0, 1, 0, 1]);619 t.end();620 });621 t.test('color spec default', (t) => {622 const f = createFunction({623 property: 'foo',624 type: 'categorical',625 stops: [[0, 'red'], [1, 'blue']]626 }, {627 type: 'color',628 default: 'lime'629 });630 t.deepEqual(f(0, {}), [0, 1, 0, 1]);631 t.deepEqual(f(0, {foo: 3}), [0, 1, 0, 1]);632 t.end();633 });634 t.test('boolean', (t) => {635 const f = createFunction({636 property: 'foo',637 type: 'categorical',638 stops: [[true, 'true'], [false, 'false']]639 }, {640 type: 'string'641 });642 t.equal(f(0, {foo: true}), 'true');643 t.equal(f(0, {foo: false}), 'false');644 t.end();645 });646 t.end();647});648test('identity function', (t) => {649 t.test('number', (t) => {650 const f = createFunction({651 property: 'foo',652 type: 'identity'653 }, {654 type: 'number'655 });656 t.equal(f(0, {foo: 1}), 1);657 t.end();658 });659 t.test('number function default', (t) => {660 const f = createFunction({661 property: 'foo',662 type: 'identity',663 default: 1664 }, {665 type: 'string'666 });667 t.equal(f(0, {}), 1);668 t.end();669 });670 t.test('number spec default', (t) => {671 const f = createFunction({672 property: 'foo',673 type: 'identity'674 }, {675 type: 'string',676 default: 1677 });678 t.equal(f(0, {}), 1);679 t.end();680 });681 t.test('color', (t) => {682 const f = createFunction({683 property: 'foo',684 type: 'identity'685 }, {686 type: 'color'687 });688 t.deepEqual(f(0, {foo: 'red'}), [1, 0, 0, 1]);689 t.deepEqual(f(1, {foo: 'blue'}), [0, 0, 1, 1]);690 t.end();691 });692 t.test('color function default', (t) => {693 const f = createFunction({694 property: 'foo',695 type: 'identity',696 default: 'red'697 }, {698 type: 'color'699 });700 t.deepEqual(f(0, {}), [1, 0, 0, 1]);701 t.end();702 });703 t.test('color spec default', (t) => {704 const f = createFunction({705 property: 'foo',706 type: 'identity'707 }, {708 type: 'color',709 default: 'red'710 });711 t.deepEqual(f(0, {}), [1, 0, 0, 1]);712 t.end();713 });714 t.test('color invalid', (t) => {715 const f = createFunction({716 property: 'foo',717 type: 'identity'718 }, {719 type: 'color',720 default: 'red'721 });722 t.deepEqual(f(0, {foo: 'invalid'}), [1, 0, 0, 1]);723 t.end();724 });725 t.test('property type mismatch, function default', (t) => {726 const f = createFunction({727 property: 'foo',728 type: 'identity',729 default: 'default'730 }, {731 type: 'string'732 });733 t.equal(f(0, {foo: 0}), 'default');734 t.end();735 });736 t.test('property type mismatch, spec default', (t) => {737 const f = createFunction({738 property: 'foo',739 type: 'identity'740 }, {741 type: 'string',742 default: 'default'743 });744 t.equal(f(0, {foo: 0}), 'default');745 t.end();746 });747 t.end();748});749test('unknown function', (t) => {750 t.throws(() => createFunction({751 type: 'nonesuch', stops: [[]]752 }, {753 type: 'string'754 }), /Unknown function type "nonesuch"/);755 t.end();756});757test('isConstant', (t) => {758 t.test('constant', (t) => {759 const f = createFunction(1, {760 type: 'string'761 });762 t.ok(f.isZoomConstant);763 t.ok(f.isFeatureConstant);764 t.end();765 });766 t.test('zoom', (t) => {767 const f = createFunction({768 stops: [[1, 1]]769 }, {770 type: 'string'771 });772 t.notOk(f.isZoomConstant);773 t.ok(f.isFeatureConstant);774 t.end();775 });776 t.test('property', (t) => {777 const f = createFunction({778 stops: [[1, 1]],779 property: 'mapbox'780 }, {781 type: 'string'782 });783 t.ok(f.isZoomConstant);784 t.notOk(f.isFeatureConstant);785 t.end();786 });787 t.test('zoom + property', (t) => {788 const f = createFunction({789 stops: [[{ zoom: 1, data: 1 }, 1]],790 property: 'mapbox'791 }, {792 type: 'string'793 });794 t.notOk(f.isZoomConstant);795 t.notOk(f.isFeatureConstant);796 t.end();797 });798 t.end();...

Full Screen

Full Screen

javascriptthehardparts-iterations-notes.js

Source:javascriptthehardparts-iterations-notes.js Github

copy

Full Screen

...36// getNextNumber()37// if it's currently at 4, how is it going to be able to give 5 next if it doesn't retain memory?38// we give it 'superpowers'39// by making it a function within a function40function createFunction() {41 function add2(num) {42 return num + 2;43 }44 return add2;45}46const generatedFunc = createFunction();47const result = generatedFunc(3); // 548// save createFunction49// invoke createFunction50// the righthand side of generatedFunc cannot be saved right now, because it is not a definition, it is actually the running of the function because of the parentheses51// this is probably one of the most important concepts in JavaScript beside the eventLoop52// 53// once createFunction is invoked and is finished, the data is deleted except for what is returned54// JavaScript never works its way back up the thread55// JavaScript only goes one way, single-threadedly, if it seems it's working its way back up, it's really looking up its DataStore or memory56// function definition is the 'code of function'57// you can not save an actual function invocation, you can only save a value58// so in generatedFunc = createFunction(); it is just telling it to run the code, but it is NOT saving it as createFunction();59// in reality, after createFunction(); is called, generatedFunc is actually being defined as add2 or whatever createFunction() returns;60// the advantage of creating a function within another function this way is it is able to 'remember'61// creating a function that returns elements one by one62function createFunction(array){63 let i = 0;64 function inner(){65 const element = array[i];66 i++;67 return element;68 }69 return inner;70}71const returnNextElement = createFunction([4, 5, 6]);72const element1 = returnNextElement();73const element2 = returnNextElement();74console.log('element1', element1);75console.log('element2', element2);76createFunction();77// amazingly, the backpack is carried through as [4, 5, 6], in MEMORY! THIS IS THE MAGIC!78// we now have functions that have two memories, one with temp memory, and another with permanent memory! This is the key!79// this permanent memory is stored inside the function inside the hidden property called SCOPE!...

Full Screen

Full Screen

fs.js

Source:fs.js Github

copy

Full Screen

...4 let callback = args.pop()5 fn(...args).then(result => callback(undefined, result), error => callback(error))6 }7}8export var access = createFunction(libc.access)9export var chmod = createFunction(libc.chmod)10export var chown = createFunction(libc.chown)11export var close = createFunction(libc.close)12export var fchmod = createFunction(libc.fchmod)13export var fchown = createFunction(libc.fchown)14export var fdatasync = createFunction(libc.fdatasync)15export var fstat = createFunction(libc.fstat)16export var fsync = createFunction(libc.fsync)17export var ftruncate = createFunction(libc.ftruncate)18export var lchmod = createFunction(libc.lchmod)19export var lchown = createFunction(libc.lchown)20export var link = createFunction(libc.link)21export var lstat = createFunction(libc.lstat)22export var mkdir = createFunction(libc.mkdir)23export var open = createFunction(libc.open)24export var readdir = createFunction(libc.readdir)25export var readlink = createFunction(libc.readlink)26export var realpath = createFunction(libc.realpath)27export var rename = createFunction(libc.rename)28export var rmdir = createFunction(libc.rmdir)29export var stat = createFunction(libc.stat)30export var symlink = createFunction(libc.symlink)31export var truncate = createFunction(libc.truncate)32export var unlink = createFunction(libc.unlink)33export var write = createFunction(libc.write)34export var read = createFunction(async function read (fd, buffer, offset, length, position) {35 let syscall = global.syscall36 await syscall('lseek', fd, position)37 if (offset) buffer = buffer.slice(offset)38 return await syscall('read', fildes, buffer, length)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const {createFunction} = require('playwright/lib/server/supplements/recorder/recorderSupplement');2const {chromium} = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const fn = createFunction(page, () => document.querySelector('h1').textContent);7 console.log(await fn());8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createFunction } = require('playwright-core/lib/server/frames');2const { Page } = require('playwright-core/lib/server/page');3const { Frame } = require('playwright-core/lib/server/frame');4const { ElementHandle } = require('playwright-core/lib/server/dom');5const createFunction = require('playwright-core/lib/server/frames').createFunction;6const { createFunction } = require('playwright-core/lib/server/frames');7const createFunction = require('playwright-core/lib/server/frames').createFunction;8const { createFunction } = require('playwright-core/lib/server/frames');9const createFunction = require('playwright-core/lib/server/frames').createFunction;10const { createFunction } = require('playwright-core/lib/server/frames');11const createFunction = require('playwright-core/lib/server/frames').createFunction;12const { createFunction } = require('playwright-core/lib/server/frames');13const createFunction = require('playwright-core/lib/server/frames').createFunction;14const { createFunction } = require('playwright-core/lib/server/frames');15const createFunction = require('playwright-core/lib/server/frames').createFunction;16const { createFunction } = require('playwright-core/lib/server/frames');17const createFunction = require('playwright-core/lib/server/frames').createFunction;18const { createFunction } = require('playwright-core/lib/server/frames');19const createFunction = require('playwright-core/lib/server/

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createFunction } = require('playwright-core/lib/server/supplements/recorder/recorderSupplement');2const path = require('path');3const fs = require('fs');4const playwright = require('playwright-core');5(async () => {6 const browser = await playwright.chromium.launch({ headless: false });7 const context = await browser.newContext();8 const page = await context.newPage();9 await page.click('input[aria-label="Search"]');10 await page.fill('input[aria-label="Search"]', 'Hello World');11 await page.press('input[aria-label="Search"]', 'Enter');12 const text = await page.textContent('html');13 console.log(text);14 const script = createFunction(page);15 fs.writeFileSync(path.join(__dirname, 'script.js'), script);16 await browser.close();17})();18const { chromium } = require('playwright-core');19(async () => {20 const browser = await chromium.launch();21 const context = await browser.newContext();22 const page = await context.newPage();23 await page.click('input[aria-label="Search"]');24 await page.fill('input[aria-label="Search"]', 'Hello World');25 await page.press('input[aria-label="Search"]', 'Enter');26 const text = await page.textContent('html');27 console.log(text);28 await browser.close();29})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createFunction } = require('playwright-core/lib/server/frames');2const { Page } = require('playwright-core/lib/server/page');3const { Frame } = require('playwright-core/lib/server/frame');4const { CDPSession } = require('playwright-core/lib/cjs/pw-chromium/cjs/protocol/chromium');5const { createJSHandle } = require('playwright-core/lib/server/JSHandle');6const { createFunction } = require('playwright-core/lib/server/frames');7const { Page } = require('playwright-core/lib/server/page');8const { Frame } = require('playwright-core/lib/server/frame');9const { CDPSession } = require('playwright-core/lib/cjs/pw-chromium/cjs/protocol/chromium');10const { createJSHandle } = require('playwright-core/lib/server/JSHandle');11const { createFunction } = require('playwright-core/lib/server/frames');12const { Page } = require('playwright-core/lib/server/page');13const { Frame } = require('playwright-core/lib/server/frame');14const { CDPSession } = require('playwright-core/lib/cjs/pw-chromium/cjs/protocol/chromium');15const { createJSHandle } = require('playwright-core/lib/server/JSHandle');16const { createFunction } = require('playwright-core/lib/server/frames');17const { Page } = require('playwright-core/lib/server/page');18const { Frame } = require('playwright-core/lib/server/frame');19const { CDPSession } = require('playwright-core/lib/cjs/pw-chromium/cjs/protocol/chromium');20const { createJSHandle } = require('playwright-core/lib/server/JSHandle');21const { createFunction } = require('playwright-core/lib/server/frames');22const { Page } = require('playwright-core/lib/server/page');23const { Frame } = require('playwright-core/lib/server/frame');24const { CDPSession } = require('playwright-core/lib/cjs/pw-chromium/cjs/protocol/chromium');25const { createJSHandle } = require('playwright-core/lib/server/JSHandle');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createFunction } = require('playwright-core/lib/server/supplements/recorder/recorderSupplement');2const { test, expect } = require('@playwright/test');3test('Test', async ({ page }) => {4 const myFunc = createFunction(page, 'function() { console.log("Hello World"); }');5 await myFunc();6});7const { test, expect } = require('@playwright/test');8test('Test', async ({ page }) => {9 await page.evaluate(() => {10 console.log("Hello World");11 });12});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createFunction } = require('playwright-core/lib/server/injected/injectedScript');2const { createFunctionString } = require('playwright-core/lib/server/injected/injectedScriptSource');3const { context } = require('playwright-core/lib/server/browserContext');4const { Page } = require('playwright-core/lib/server/page');5const { Frame } = require('playwright-core/lib/server/frames');6const { JSHandle } = require('playwright-core/lib/server/injected/jsHandle');7const functionString = createFunctionString(function () {8 function checkElement(element) {9 if (element.tagName === 'INPUT') {10 return true;11 }12 return false;13 }14 function checkElementValue(element) {15 const value = element.value;16 if (value === 'test') {17 return true;18 }19 return false;20 }21 function checkElementClass(element) {22 const className = element.className;23 if (className === 'test') {24 return true;25 }26 return false;27 }28 function checkElementText(element) {29 const text = element.innerText;30 if (text === 'test') {31 return true;32 }33 return false;34 }35 function checkElementName(element) {36 const name = element.name;37 if (name === 'test') {38 return true;39 }40 return false;41 }42 function checkElementId(element) {43 const id = element.id;44 if (id === 'test') {45 return true;46 }47 return false;48 }49 function checkElementPlaceholder(element) {50 const placeholder = element.placeholder;51 if (placeholder === 'test') {52 return true;53 }54 return false;55 }56 function checkElementAriaLabel(element) {57 const ariaLabel = element.getAttribute('aria-label');58 if (ariaLabel === 'test') {59 return true;60 }61 return false;62 }63 function checkElementAriaLabelledby(element) {64 const ariaLabelledby = element.getAttribute('aria-labelledby');65 if (ariaLabelledby === 'test') {66 return true;67 }68 return false;69 }70 function checkElementAriaDescribedby(element) {71 const ariaDescribedby = element.getAttribute('aria-describedby');72 if (ariaDescribedby === 'test') {73 return true;74 }75 return false;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { createFunction } from 'playwright-core/lib/server/injected/injectedScript';2const func = createFunction(() => {3 return document.location.href;4});5const result = await page.evaluate(func);6console.log(result);7import { createFunction } from 'playwright-core/lib/server/injected/injectedScript';8const func = createFunction(() => {9 return document.location.href;10});11const result = await page.evaluate(func);12console.log(result);13import { createFunction } from 'playwright-core/lib/server/injected/injectedScript';14const func = createFunction(() => {15 return document.location.href;16});17const result = await page.evaluate(func);18console.log(result);19import { createFunction } from 'playwright-core/lib/server/injected/injectedScript';20const func = createFunction(() => {21 return document.location.href;22});23const result = await page.evaluate(func);24console.log(result);25import { createFunction } from 'playwright-core/lib/server/injected/injectedScript';26const func = createFunction(() => {27 return document.location.href;28});29const result = await page.evaluate(func);30console.log(result);31import { createFunction } from 'playwright-core/lib/server/injected/injectedScript';32const func = createFunction(() => {33 return document.location.href;34});35const result = await page.evaluate(func);36console.log(result);37import { createFunction } from 'playwright-core/lib/server/injected/injectedScript';38const func = createFunction(() => {39 return document.location.href;40});41const result = await page.evaluate(func);42console.log(result);43import { createFunction } from 'playwright-core/lib/server/injected/injectedScript';44const func = createFunction(() => {45 return document.location.href;46});47const result = await page.evaluate(func);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createFunction } = require('playwright/internal');2const { test } = require('@playwright/test');3const myCustomFunction = createFunction(async ({ page }, selector) => {4 await page.waitForSelector(selector);5 const element = await page.$(selector);6 return element;7});8test('My custom function', async ({ page }) => {9 const element = await myCustomFunction(page, 'text=Get started');10 await element.click();11});12const { test } = require('@playwright/test');13test('My custom function', async ({ page }) => {14 const element = await myCustomFunction(page, 'text=Get started');15 await element.click();16});17module.exports = { myCustomFunction };18Now, in the file test.spec.js , import the variable myCustomFunction using the following line:19const { myCustomFunction } = require('./test');20test('My custom function', async ({ page }) => {21 const element = await myCustomFunction(page, 'text=Get started');22 await element.click();23});

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful