How to use GETTER_NAME method in Jest

Best JavaScript code snippet using jest

io.js

Source:io.js Github

copy

Full Screen

1builder.selenium2.io = {};2/**3 * Code for exporting/importing Selenium 2 scripts in a variety of formats.4*/5builder.selenium2.io.parseScript = function(text, path) {6 var scriptJSON = JSON.parse(text);7 var script = new builder.Script(builder.selenium2);8 script.path = {9 'where': path.where,10 'path': path.path,11 'format': builder.selenium2.io.formats[0]12 };13 14 var known_unknowns = [];15 var ko_string = "";16 for (var i = 0; i < scriptJSON.steps.length; i++) {17 var typeName = scriptJSON.steps[i].type;18 if (!builder.selenium2.stepTypes[typeName] && known_unknowns.indexOf(typeName) == -1) {19 if (known_unknowns.length > 0) {20 ko_string += ", ";21 }22 ko_string += typeName;23 known_unknowns.push(typeName);24 }25 }26 if (known_unknowns.length > 0) {27 throw new Error(_t("sel1_no_command_found") + ": " + ko_string);28 }29 30 for (var i = 0; i < scriptJSON.steps.length; i++) {31 script.steps.push(builder.stepFromJSON(scriptJSON.steps[i], builder.selenium2));32 }33 34 script.timeoutSeconds = scriptJSON.timeoutSeconds || 60;35 if (scriptJSON.data) {36 script.data = scriptJSON.data;37 }38 if (scriptJSON.inputs) {39 script.inputs = scriptJSON.inputs;40 }41 42 return script;43};44builder.selenium2.io.jsonToLoc = function(jsonO) {45 var method = builder.locator.methodForName(builder.selenium2, jsonO.type);46 var values = {};47 values[method] = ["" + jsonO.value];48 return new builder.locator.Locator(method, 0, values);49};50builder.selenium2.io.loadScriptJSON = function(path) {51 var file = null;52 if (path == null) {53 file = sebuilder.showFilePicker(window, _t('select_a_file'), 54 Components.interfaces.nsIFilePicker.modeOpen,55 "extensions.seleniumbuilder3.loadSavePath",56 function(fp) { return fp.file; });57 } else {58 file = sebuilder.SeFileUtils.getFile(path);59 }60 var sis = sebuilder.SeFileUtils.openFileInputStream(file);61 var script = JSON.parse(sebuilder.SeFileUtils.getUnicodeConverter('UTF-8').ConvertToUnicode(sis.read(sis.available())));62 sis.close();63 script.path = {64 where: "local",65 path: file.path66 };67 return script;68};69builder.selenium2.io.getScriptDefaultRepresentation = function(script, name, params) {70 return builder.selenium2.io.formats[0].format(script, name, params || {});71};72builder.selenium2.io.defaultRepresentationExtension = ".json";73builder.selenium2.io.saveScript = function(script, format, path, callback) {74 if (format.get_params) {75 format.get_params(script, function(params) {76 callback(builder.selenium2.io.saveScriptWithParams(script, format, path, params));77 });78 } else {79 callback(builder.selenium2.io.saveScriptWithParams(script, format, path, {}));80 }81};82builder.selenium2.io.saveScriptWithParams = function(script, format, path, params) {83 try {84 var file = null;85 if (path == null) {86 file = sebuilder.showFilePicker(window, _t('save_as'),87 Components.interfaces.nsIFilePicker.modeSave,88 "extensions.seleniumbuilder3.loadSavePath",89 function(fp) { return fp.file; },90 format.extension);91 } else {92 file = sebuilder.SeFileUtils.getFile(path);93 }94 if (file != null) {95 var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"].96 createInstance(Components.interfaces.nsIFileOutputStream);97 outputStream.init(file, 0x02 | 0x08 | 0x20, 0644, 0);98 var converter = sebuilder.SeFileUtils.getUnicodeConverter('UTF-8');99 var text = converter.ConvertFromUnicode(format.format(script, file.leafName, params));100 outputStream.write(text, text.length);101 var fin = converter.Finish();102 if (fin.length > 0) {103 outputStream.write(fin, fin.length);104 }105 outputStream.close();106 var path = {107 where: "local",108 path: file.path,109 format: format110 };111 if (builder.selenium2.io.isSaveFormat(format)) {112 script.path = path;113 } else {114 script.exportpath = path;115 }116 return true;117 } else {118 return false;119 }120 } catch (err) {121 alert("" + err);122 return false;123 }124};125builder.selenium2.io.formats = [];126builder.selenium2.io.isSaveFormat = function(format) {127 return format && format == builder.selenium2.io.formats[0];128};129builder.selenium2.io.makeDoSubs = function(script, step, name, userParams, used_vars, lang_info) {130 var doSubs = function(line, extras) {131 if (extras) {132 for (var k in extras) {133 var v = doSubs(extras[k]);134 line = line.replace(new RegExp("\\{" + k + "\\}", "g"), v);135 }136 }137 line = line.replace(new RegExp("\\{stepTypeName\\}", "g"), step.type.name);138 for (var k in userParams) {139 line = line.replace(new RegExp("\\{" + k + "\\}", "g"), userParams[k]);140 }141 var pNames = step.getParamNames();142 for (var j = 0; j < pNames.length; j++) {143 if (step.type.getParamType(pNames[j]) == "locator") {144 line = line.replace(new RegExp("\\{" + pNames[j] + "\\}", "g"), lang_info.escapeValue(step.type, step[pNames[j]].getValue(), pNames[j]));145 line = line.replace(new RegExp("\\{" + pNames[j] + "By\\}", "g"), lang_info.locatorByForType(step.type, step[pNames[j]].getName(builder.selenium2), j + 1));146 } else {147 line = line.replace(new RegExp("\\{" + pNames[j] + "\\}", "g"), lang_info.escapeValue(step.type, step[pNames[j]], pNames[j]));148 }149 }150 // Depending on whether the step is negated, put in the appropriate logical nots.151 if (step.negated) {152 line = line.replace(new RegExp("\\{posNot\\}", "g"), "");153 line = line.replace(new RegExp("\\{negNot\\}", "g"), lang_info.not);154 } else {155 line = line.replace(new RegExp("\\{posNot\\}", "g"), lang_info.not);156 line = line.replace(new RegExp("\\{negNot\\}", "g"), "");157 }158 // Finally, sub in any lang_info keys required.159 for (var k in lang_info) {160 line = line.replace(new RegExp("\\{" + k + "\\}", "g"), lang_info[k]);161 }162 // Replace ${foo} with the necessary invocation of the variable, eg "String foo" or "var foo".163 var l2 = "";164 var hasDollar = false;165 var insideVar = false;166 var varName = "";167 for (var j = 0; j < line.length; j++) {168 var ch = line.substring(j, j + 1);169 if (insideVar) {170 if (ch == "}") {171 var spl = varName.split(":", 2);172 var varType = spl.length == 2 ? spl[1] : null;173 varName = spl[0];174 if (used_vars[varName]) {175 l2 += lang_info.usedVar(varName, varType);176 } else {177 l2 += lang_info.unusedVar(varName, varType);178 used_vars[varName] = true;179 }180 insideVar = false;181 hasDollar = false;182 varName = "";183 } else {184 varName += ch;185 }186 } else {187 // !insideVar188 if (hasDollar) {189 if (ch == "{") { insideVar = true; } else { hasDollar = false; l2 += "$" + ch; }190 } else {191 if (ch == "$") { hasDollar = true; } else { l2 += ch; }192 }193 }194 }195 196 return l2;197 };198 199 return doSubs;200};201builder.selenium2.io.lang_infos = {};202builder.selenium2.io.addLangFormatter = function(lang_info) {203 builder.selenium2.io.lang_infos[lang_info.name] = lang_info;204 builder.selenium2.io.formats.push(builder.selenium2.io.createLangFormatter(lang_info));205};206builder.selenium2.io.addDerivedLangFormatter = function(original_name, lang_info_diff) {207 var original = builder.selenium2.io.lang_infos[original_name];208 if (original) {209 var new_info = {};210 for (var k in original) {211 new_info[k] = original[k];212 }213 for (var k in lang_info_diff) {214 new_info[k] = lang_info_diff[k];215 }216 builder.selenium2.io.addLangFormatter(new_info);217 }218};219builder.selenium2.io.canExport = function(lang_info, stepType) {220 var lft = lang_info.lineForType[stepType.name];221 if (lft !== undefined) { return true; }222 if (!lang_info.getters || !lang_info.boolean_getters) { return false; }223 var booleanVersion = false;224 for (var b = 0; b < 2; b++) {225 var stepFlavors = ["assert", "verify", "waitFor", "store"];226 for (var f = 0; f < stepFlavors.length; f++) {227 var flavor_key = (booleanVersion ? "boolean_" : "") + stepFlavors[f];228 if (stepType.name.startsWith(stepFlavors[f]) && lang_info[flavor_key] !== undefined) {229 var getter_name = stepType.name.substring(stepFlavors[f].length);230 var getter = booleanVersion ? lang_info.boolean_getters[getter_name] : lang_info.getters[getter_name];231 if (getter !== undefined) { return true; }232 }233 }234 booleanVersion = true;235 }236 return false;237};238builder.selenium2.io.createLangFormatter = function(lang_info) {239 return {240 name: lang_info.name,241 extension: lang_info.extension,242 get_params: lang_info.get_params || null,243 format: function(script, name, userParams) {244 var t = "";245 var start = lang_info.start;246 for (var k in lang_info) {247 start = start.replace(new RegExp("\\{" + k + "\\}", "g"), lang_info[k]);248 }249 for (var k in userParams) {250 start = start.replace(new RegExp("\\{" + k + "\\}", "g"), userParams[k]);251 }252 start = start.replace(/\{scriptName\}/g, name.substr(0, name.indexOf(".")));253 start = start.replace(/\{timeoutSeconds\}/g, "" + script.timeoutSeconds);254 t += start;255 var used_vars = {};256 stepsLoop: for (var i = 0; i < script.steps.length; i++) {257 var step = script.steps[i];258 var doSubs = builder.selenium2.io.makeDoSubs(script, step, name, userParams, used_vars, lang_info);259 var line = lang_info.lineForType[step.type.name];260 if (typeof line != 'undefined') {261 if (line instanceof Function) {262 t += line(step, lang_info.escapeValue, userParams, doSubs);263 } else {264 t += doSubs(line);265 }266 } else {267 var booleanVersion = false;268 for (var b = 0; b < 2; b++) {269 var stepFlavors = ["assert", "verify", "waitFor", "store"];270 for (var f = 0; f < stepFlavors.length; f++) {271 var flavor_key = (booleanVersion ? "boolean_" : "") + stepFlavors[f];272 if (step.type.name.startsWith(stepFlavors[f]) && lang_info[flavor_key] !== undefined) {273 var flavor = lang_info[flavor_key];274 var getter_name = step.type.name.substring(stepFlavors[f].length);275 var getter = booleanVersion ? lang_info.boolean_getters[getter_name] : lang_info.getters[getter_name];276 if (getter !== undefined) {277 if (flavor instanceof Function) {278 t += flavor(step, lang_info.escapeValue, doSubs, getter);279 } else {280 t += doSubs(flavor, getter);281 }282 continue stepsLoop;283 }284 }285 }286 booleanVersion = true;287 }288 throw(_t('sel2_cant_export_step_type', step.type.name));289 }290 }291 var end = lang_info.end;292 for (var k in lang_info) {293 end = end.replace(new RegExp("\\{" + k + "\\}", "g"), lang_info[k]);294 }295 for (var k in userParams) {296 end = end.replace(new RegExp("\\{" + k + "\\}", "g"), userParams[k]);297 }298 end = end.replace(/\{scriptName\}/g, name.substr(0, name.indexOf(".")));299 t += end;300 return t;301 },302 canExport: function(stepType) {303 return builder.selenium2.io.canExport(lang_info, stepType);304 },305 nonExportables: function(script) {306 var nes = [];307 for (var i = 0; i < script.steps.length; i++) {308 var step = script.steps[i];309 if (nes.indexOf(step.type.name) == -1 && !builder.selenium2.io.canExport(lang_info, step.type)) {310 nes.push(step.type.name);311 }312 }313 return nes;314 }315 };316};317builder.selenium2.io.suiteFormats = [];318builder.selenium2.io.getSuiteExportFormatsFor = function(format) {319 var formats = [];320 for (var i = 0; i < builder.selenium2.io.suiteFormats.length; i++) {321 var f = builder.selenium2.io.suiteFormats[i];322 if (f.scriptFormatName == format.name) {323 formats.push(f);324 }325 }326 return formats;327};328builder.selenium2.io.getSuiteExportFormats = function(path) {329 var fs = [];330 if (path) {331 fs.push(makeSuiteExportEntry("Save to " + path.path, path.format, path));332 }333 for (var i = 0; i < builder.selenium2.io.suiteFormats.length; i++) {334 fs.push(makeSuiteExportEntry(builder.selenium2.io.suiteFormats[i].name, builder.selenium2.io.suiteFormats[i], null));335 }336 return fs;337};338function makeSuiteExportEntry(name, format, path) {339 return {340 "name": name,341 "save": function(scripts) {342 return builder.selenium2.io.saveSuite(format, scripts, path);343 }344 };345};346builder.selenium2.io.saveSuite = function(scripts, path) {347 return builder.selenium2.io.saveSuiteAsFormat(builder.selenium2.io.suiteFormats[0], scripts, path);348};349builder.selenium2.io.exportSuite = function(scripts, format) {350 return builder.selenium2.io.saveSuiteAsFormat(format, scripts, null);351};352builder.selenium2.io.saveSuiteAsFormat = function(format, scripts, path) {353 try {354 var file = null;355 if (path == null) {356 file = sebuilder.showFilePicker(window, _t('save_as'),357 Components.interfaces.nsIFilePicker.modeSave,358 "extensions.seleniumbuilder3.loadSavePath",359 function(fp) { return fp.file; },360 format.extension);361 } else {362 file = sebuilder.SeFileUtils.getFile(path.path);363 }364 if (file != null) {365 var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance( Components.interfaces.nsIFileOutputStream);366 outputStream.init(file, 0x02 | 0x08 | 0x20, 0644, 0);367 var converter = sebuilder.SeFileUtils.getUnicodeConverter('UTF-8');368 var path = { 'path': file.path, 'where': 'local', 'format': format };369 var text = converter.ConvertFromUnicode(format.format(scripts, path));370 outputStream.write(text, text.length);371 var fin = converter.Finish();372 if (fin.length > 0) {373 outputStream.write(fin, fin.length);374 }375 outputStream.close();376 return path;377 } else {378 return false;379 }380 } catch (err) {381 alert("" + err);382 return false;383 }384};385builder.selenium2.io.parseSuite = function(text, path, callback) {386 var suite = null;387 try {388 suite = JSON.parse(text);389 } catch (e) {390 callback(null, _t('could_not_open_suite'));391 return;392 }393 if (!suite.type || suite.type !== "suite" || !suite.scripts || suite.scripts.length == 0) {394 callback(null, _t('could_not_open_suite'));395 return;396 }397 var si = {398 'scripts': [],399 'path': {'path': path.path, 'where': path.where, 'format': builder.selenium2.io.suiteFormats[0] },400 'shareState': !!suite.shareState401 };402 function loadScript(i) {403 builder.io.loadPath(suite.scripts[i], path, function(loaded) {404 if (loaded) {405 si.scripts.push(builder.selenium2.io.parseScript(loaded.text, loaded.path));406 }407 if (i == suite.scripts.length - 1) {408 callback(si);409 } else {410 loadScript(i + 1);411 }412 });413 }414 loadScript(0);415};416builder.selenium2.io.getSaveFormat = function() {417 return builder.selenium2.io.formats[0];418};419builder.selenium2.io.getSaveSuiteFormat = function() {420 return builder.selenium2.io.suiteFormats[0];421};...

Full Screen

Full Screen

dict.js

Source:dict.js Github

copy

Full Screen

1/*jslint nomen: true, vars: true */2/*global interstate,esprima,able,uid,console */3(function (ist) {4 "use strict";5 var cjs = ist.cjs,6 _ = ist._;7 8 ist.POINTERS_PROPERTY = {};9 ist.MANIFESTATIONS_PROPERTY = {};10 11 ist.is_inherited = function (pcontext) {12 return ist.inherited_root(pcontext) !== undefined;13 };14 ist.inherited_root = function (pcontext) {15 var child, parent;16 child = pcontext.points_at();17 var inh = false,18 child_src,19 i;20 for (i = pcontext.length() - 2; i >= 0; i -= 1) {21 parent = pcontext.points_at(i);22 child_src = parent.src_for_prop(child, pcontext.slice(0, i + 1));23 if (child_src === parent) {24 if (inh) {25 return pcontext.slice(0, i + 3);26 }27 } else if (child_src !== undefined) {28 inh = true;29 }30 31 child = parent;32 }33 return undefined;34 };35 36 ist.Dict = function (options, defer_initialization) {37 options = _.extend({38 value: {},39 keys: [],40 values: [],41 has_protos: true,42 has_copies: true43 }, options);44 ist.Dict.superclass.constructor.call(this, options, defer_initialization);45 46 this.type = "ist_dict";47 };48 49 (function (My) {50 _.proto_extend(My, ist.BasicObject);51 var proto = My.prototype;52 53 proto.initialize = function (options) {54 My.superclass.initialize.apply(this, arguments);55 ist.install_instance_builtins(this, options, My);56 var direct_props = this.direct_props();57 direct_props.setValueEqualityCheck(function (info1, info2) {58 return info1.value === info2.value;59 });60 };61 62 My.builtins = {63 "direct_protos": {64 "default": function () { return cjs.array(); },65 getter_name: "direct_protos",66 setter_name: "_set_direct_protos",67 env_visible: true,68 env_name: "prototypes",69 destroy: function(me) {70 me.destroy(true);71 }72 },73 74 "direct_attachments": {75 "default": function () { return []; },76 getter_name: "direct_attachments",77 destroy: function(me) {78 if (cjs.isArrayConstraint(me)) {79 me.forEach(function(attachment) {80 attachment.destroy(true);81 });82 me.destroy(true);83 } else if(_.isArray(me)) {84 _.each(me, function(attachment) {85 attachment.destroy(true);86 });87 }88 }89 },90 91 "direct_props": {92 "default": function () {93 var keys = this.options.keys,94 values = _.map(this.options.values, function(v) {95 return {96 value: v,97 owner: this98 };99 }, this),100 value = {};101 _.each(this.options.value, function(v, k) {102 value[k] = {103 value: v,104 owner: this105 };106 }, this);107 var rv = cjs.map({108 keys: keys,109 values: values,110 value: value111 });112 return rv;113 },114 getter_name: "direct_props",115 destroy: function(me) {116 me.forEach(function(prop_val, name) {117 if(prop_val.value.destroy) {118 prop_val.value.destroy(true);119 }120 delete prop_val.owner;121 delete prop_val.value;122 });123 me.destroy(true);124 }125 },126 127 "copies": {128 start_with: function () { 129 return cjs.constraint(new ist.Cell({str: ""}));130 },131 env_visible: false,132 env_name: "copies",133 getter: function (me) { return me.get(); },134 setter: function (me, val) {135 var old_val = me.get();136 if(old_val && old_val.destroy) {137 old_val.destroy(true);138 }139 me.set(val, true);140 },141 destroy: function(me) {142 var val = me.get();143 if(val && val.destroy) {144 val.destroy();145 }146 me.destroy(true);147 }148 }149 };150 151 ist.install_proto_builtins(proto, My.builtins);152 153 //154 // === DIRECT PROTOS ===155 //156 157 proto.has_protos = function () {158 return this.options.has_protos;159 };160 proto.has_copies = function() {161 return this.options.has_copies;162 };163 164 165 //166 // === DIRECT PROPERTIES ===167 //168 169 proto.set = proto.set_prop = proto._set_direct_prop = function (name, value, options) {170 var index,171 info = _.extend({172 value: value,173 owner: this174 }, options);175 this.direct_props().put(name, info, info.index);176 return this;177 };178 proto.unset = proto.unset_prop = proto._unset_direct_prop = function (name) {179 this.direct_props().remove(name);180 return this;181 };182 proto._get_direct_prop = function (name) {183 var info = this._get_direct_prop_info(name);184 if (info) {185 return info.value;186 } else {187 return undefined;188 }189 };190 proto._get_direct_prop_info = function (name) {191 return this.direct_props().get(name);192 };193 proto._has_direct_prop = function (name) {194 return this.direct_props().has(name);195 };196 proto.move = proto.move_prop = proto._move_direct_prop = function (name, to_index) {197 this.direct_props().move(name, to_index);198 return this;199 };200 proto.index = proto.prop_index = proto._direct_prop_index = function (name) {201 return this.direct_props().indexOf(name);202 };203 proto.rename = proto._rename_direct_prop = function (from_name, to_name) {204 if (this._has_direct_prop(to_name)) {205 throw new Error("Already a property with name " + to_name);206 } else {207 var direct_props = this.direct_props();208 var keyIndex = direct_props.indexOf(from_name);209 if (keyIndex >= 0) {210 var prop_val = direct_props.get(from_name);211 cjs.wait();212 direct_props.remove(from_name)213 .put(to_name, prop_val, keyIndex);214 cjs.signal();215 } else {216 throw new Error("No such property " + from_name);217 }218 }219 };220 221 proto._get_direct_prop_names = function () {222 return this.direct_props().keys();223 };224 225 //226 // === BUILTIN PROPERTIES ===227 //228 229 proto.get_builtins = function () {230 var builtins = _.clone(this.constructor.builtins);231 var supah = this.constructor.superclass;232 while (supah) {233 _.extend(builtins, supah.constructor.builtins);234 supah = supah.superclass;235 }236 return builtins;237 };238 239 var protos_array = ["prototypes"], empty_array = [];240 proto._get_builtin_prop_names = function () {241 return this.has_protos() ? protos_array : empty_array;242 /*243 var rv = [];244 _.each(this.get_builtins(), function (val, name) {245 if (val.env_visible === true) {246 if (name === "direct_protos" && !this.has_protos()) {247 return;248 }249 name = val.env_name || name;250 rv.push(name);251 }252 }, this);253 return rv;254 */255 };256 proto._get_builtin_prop_info = function (prop_name) {257 var builtins = this.get_builtins();258 var builtin_name;259 for (builtin_name in builtins) {260 if (builtins.hasOwnProperty(builtin_name)) {261 var builtin = builtins[builtin_name];262 if (builtin.env_visible === true) {263 var env_name = builtin.env_name || builtin_name;264 if (prop_name === env_name) {265 var getter_name = builtin.getter_name || "get_" + builtin_name;266 return {value: this[getter_name]()};267 }268 }269 }270 }271 };272 proto._get_builtin_prop = function (prop_name) {273 var info = this._get_builtin_prop_info(prop_name);274 if (info) {275 return info.value;276 } else {277 return undefined;278 }279 };280 proto._has_builtin_prop = function (prop_name) {281 return prop_name === "prototypes" && this.has_protos();282 /*283 var rv = false;284 return _.any(this.get_builtins(), function (val, name) {285 if (val.env_visible === true) {286 name = val.env_name || name;287 if (name === prop_name) {288 return true;289 }290 }291 return false;292 });293 */294 };295 296 //297 // === DIRECT ATTACHMENTS ===298 //299 300 proto._get_direct_attachments = function () {301 var direct_attachments = this.direct_attachments();302 if (cjs.isArrayConstraint(direct_attachments)) {303 return this.direct_attachments().toArray();304 } else if (_.isArray(direct_attachments)) {305 return direct_attachments;306 } else {307 return [direct_attachments];308 }309 };310 proto.clone = function() {311 return ist.deserialize(ist.serialize(this, false));312 };313 314 //315 // === BYE BYE ===316 //317 318 proto.destroy = function () {319 if(this.constructor === My) { this.begin_destroy(); }320 ist.unset_instance_builtins(this, My);321 My.superclass.destroy.apply(this, arguments);322 };323 324 proto.toString = function () {325 return "dict:" + this.uid;326 };327 328 proto.serialize = function (include_uid) {329 var rv = {330 has_protos: this.has_protos(),331 has_copies: this.has_copies()332 };333 if (include_uid) { rv.uid = this.id(); }334 335 var args = _.toArray(arguments);336 _.each(this.get_builtins(), function (builtin, name) {337 var getter_name = builtin._get_getter_name();338 rv[name] = ist.serialize.apply(ist, ([this[getter_name]()]).concat(args));339 }, this);340 341 return rv;342 };343 ist.register_serializable_type("dict",344 function (x) {345 return x instanceof My && x.constructor === My;346 },347 proto.serialize,348 function (obj) {349 var rest_args = _.rest(arguments);350 var serialized_options = {};351 _.each(My.builtins, function (builtin, name) {352 serialized_options[name] = obj[name];353 });354 var rv = new My({uid: obj.uid, has_protos: obj.has_protos, has_copies: obj.has_copies}, true),355 old_initialize = proto.initialize;356 rv.initialize = function () {357 delete this.initialize;358 var options = {};359 _.each(serialized_options, function (serialized_option, name) {360 options[name] = ist.deserialize.apply(ist, ([serialized_option]).concat(rest_args));361 });362 old_initialize.call(this, options);363 };364 return rv;365 });366 }(ist.Dict));...

Full Screen

Full Screen

cell.js

Source:cell.js Github

copy

Full Screen

1/*jslint nomen: true, vars: true */2/*global interstate,esprima,able,uid,console */3(function (ist) {4 "use strict";5 var cjs = ist.cjs,6 _ = ist._;7 8 ist.Cell = function (options, defer_initialization) {9 ist.Cell.superclass.constructor.apply(this, arguments);10 };11 (function (My) {12 _.proto_extend(My, ist.BasicObject);13 var proto = My.prototype;14 My.builtins = {15 "str": {16 start_with: function () { return cjs(""); },17 getter: function (me) { return me.get(); },18 setter: function (me, str) {19 me.set(str, true);20 },21 destroy: function(me) {22 me.destroy(true);23 }24 },25 "ignore_inherited_in_first_dict": {26 "default": function () { return false; }27 },28 "contextual_values": {29 "default": function () {30 return cjs.map({31 equals: ist.check_pointer_equality,32 hash: "hash"33 });34 },35 settable: false,36 serialize: false,37 destroy: function(me) {38 me.forEach(function (value) {39 value.destroy(true);40 });41 me.destroy(true);42 }43 },44 "substantiated": {45 "default": function () { return false; },46 getter_name: "is_substantiated"47 }48 };49 ist.install_proto_builtins(proto, My.builtins);50 proto.initialize = function (options) {51 My.superclass.initialize.apply(this, arguments);52 ist.install_instance_builtins(this, options, My);53 this._tree = cjs(function () {54 var str = this.get_str();55 return ist.parse(str);56 }, {57 context: this58 });59 this._is_static = cjs(function () {60 var tree = this._tree.get();61 return tree.body.length === 0 ||62 (tree.body.length === 1 &&63 tree.body[0].type === 'ExpressionStatement' &&64 tree.body[0].expression.type === 'Literal');65 }, {66 context: this67 });68 this._static_value = cjs(function() {69 var tree = this._tree.get();70 if(tree.body.length > 0) {71 return tree.body[0].expression.value;72 }73 }, {74 context: this75 });76 };77 proto.substantiate = function() {78 this.set_substantiated(true);79 this._emit("substantiated");80 };81 proto.clone = function() {82 return new ist.Cell({83 str: this.get_str()84 });85 };86 87 proto.get_ignore_inherited_in_contexts = function (pcontext) {88 var i;89 if (this.get_ignore_inherited_in_first_dict()) {90 for (i = pcontext.length() - 1; i >= 0; i -= 1) {91 var item = pcontext.points_at(i);92 if (item instanceof ist.Dict) {93 return [item];94 }95 }96 }97 return [];98 };99 100 proto.get_syntax_errors = function() {101 var tree = this._tree.get();102 return tree instanceof ist.Error ? [tree.message()] : [];103 };104 proto.constraint_in_context = function (pcontext, inherited_from_cobj) {105 if(this._is_static.get()) {106 return this._static_value.get();107 } else {108 var tree = this._tree.get();109 return ist.get_parsed_$(tree, {110 context: pcontext,111 ignore_inherited_in_contexts: this.get_ignore_inherited_in_contexts(pcontext),112 get_constraint: true,113 inherited_from_cobj: inherited_from_cobj114 });115 }116 };117 proto.value_in_context = function (pcontext, inherited_from_cobj) {118 if(this._is_static.get()) {119 return this._static_value.get();120 } else {121 var tree = this._tree.get();122 return ist.get_parsed_$(tree, {123 context: pcontext,124 ignore_inherited_in_contexts: this.get_ignore_inherited_in_contexts(pcontext),125 get_constraint: false,126 inherited_from_cobj: inherited_from_cobj127 });128 }129 };130 proto.destroy = function () {131 if(this.constructor === My) { this.begin_destroy(); }132 ist.unset_instance_builtins(this, My);133 this._tree.destroy(true);134 delete this._tree;135 this._static_value.destroy(true);136 delete this._static_value;137 this._is_static.destroy(true);138 delete this._is_static;139 My.superclass.destroy.apply(this, arguments);140 };141 142 ist.register_serializable_type("cell",143 function (x) {144 return x instanceof My;145 },146 function (include_uid) {147 var rv = { };148 if (include_uid) { rv.uid = this.id(); }149 _.each(My.builtins, function (builtin, name) {150 if (builtin.serialize !== false) {151 var getter_name = builtin.getter_name || "get_" + name;152 rv[name] = ist.serialize(this[getter_name]());153 }154 }, this);155 return rv;156 },157 function (obj) {158 var rest_args = _.rest(arguments);159 160 var serialized_options = {};161 _.each(My.builtins, function (builtin, name) {162 if (builtin.serialize !== false) {163 serialized_options[name] = obj[name];164 }165 });166 var rv = new My({uid: obj.uid}, true);167 var old_initialize = proto.initialize;168 rv.initialize = function () {169 delete this.initialize;170 var options = { };171 _.each(serialized_options, function (serialized_option, name) {172 options[name] = ist.deserialize.apply(ist, ([serialized_option]).concat(rest_args));173 });174 old_initialize.call(this, options);175 };176 return rv;177 });178 }(ist.Cell));...

Full Screen

Full Screen

oop.js

Source:oop.js Github

copy

Full Screen

1//OBJECT-ORIENTED JAVASCRIPT PROGRAMMING//2//Define and assign value to a variable in one of three ways:3var variable_name1 = "variable_value1";4const variable_name2 = "variable_value2";5//NOTE: the value of a variable set with const cannot be altered6let variable_name3 = "variable_value3";7//Update value of a variable:8variable_name1 = "variable_value4";9//Define and assign value(s) to an array:10let array_name1 = ["array_value1","array_value2","array_value3"];11let array_name2 = [1, 2, 3];12//Access value within an array:13array_name1[0]14//"array_value1"15//Define a function:16function function_1 (param1,param2) {17}18//Define and assign key:value pairs to an object (thereby creating an object literal):19const object_name1 = {key_1:"value_1", key_2:[1,2], key_3:"value_3"};20//Call the property of an object:21object_name1.key_122//"value_1"23//Access value of a (collection containing) property called on an object:24object_name1.key_2[0]25//126//Access value of a property within a property of an object:27object_name1['property_1'][index_#]['property_2'][index_#]28OR29object_name1.property_1(index_#).property_2(index_#)30//Add new property to an object literal:31object_name.new_property = value32OR33object_name['new_property'] = value34//Constructors35//Create a new constructor function:36function Constructor_name(argument_1,argument_2,argument_3,...,argument_n) {37 this.argument_1 = argument_1;38 this.argument_2 = argument_2;39 this.argument_3 = argument_3;40 ...41 this.argument_n = argument_n;42}43OR44function Constructor_name(argument_1,argument_2,argument_3,...,argument_n) {45 this.argument_1 = argument_1;46 this.argument_2 = argument_2;47 this.argument_3 = argument_3;48 ...49 this.argument_n = argument_n;50 this.additional_argument = 'Banana';51}52//Create new instance object from a constructor function:53var instance_object_name = new Constructor_name(value_1,value_2,value_3,...,value_n);54//Add a new property to an existing object:55instance_object_name.argument_4 = 1;56//Add a method to an existing object:57instance_object_name.add_1_and_2 = function () {return this.argument_1 + this.argument_2;};58//Classes59//Create a new class:60class Class_name {Constructor(argument_1,argument_2,argument_3,...,argument_n){executed_code_within_class Class_name}};61//Initialize the values of properties within a class:62class Class_name {Constructor(argument_1,argument_2,argument_3,...,argument_n){63 this.add_1_and_2 = argument_1 + argument_2;64 this.argument_3 = argument_3;65 this.argument_n = argument_n;66 this.additional_argument = 'Banana';67}};68//Add a new property to a class:69Class_name.argument_4 = 1;70//Create an instance of a class:71const instance_object_name = new Class_name(value_of_argument_1,value_of_argument_2,value_of_argument_3,...,value_of_argument_n);72//Create a method within a class:73class Class_name {Constructor(argument_1,argument_2,argument_3,...,argument_n){74 method_name(params){executed_code_returning_a_value}75}};76//Add a method to a class:77Class_name.argument_n_plus_1 = function () {executed_code};78//Call a class method:79Class_name.method_name(args)80//Getters and Setters81//Define a getter method:82get getter_name(){executed_code_returning_a_value};83//Access value of a getter method:84object_name.getter_name85OR86object_name[getter_name]87//Define a setter method:88set setter_name(){executed_code_that_accepts_value};89//Access setter method:...

Full Screen

Full Screen

obj_utils.js

Source:obj_utils.js Github

copy

Full Screen

1/*jslint nomen: true, vars: true */2/*global interstate,esprima,able,uid,console */3(function (ist) {4 "use strict";5 var cjs = ist.cjs,6 _ = ist._;7 ist.install_proto_builtins = function (proto, builtins) {8 _.each(builtins, function (builtin, name) {9 var getter_name = builtin.getter_name || "get_" + name;10 builtin._get_getter_name = function () { return getter_name; };11 if (_.isFunction(builtin.getter)) {12 proto[getter_name] = function () {13 return builtin.getter.apply(this, ([this._builtins[name]]).concat(_.toArray(arguments)));14 };15 } else if (builtin.gettable !== false) {16 proto[getter_name] = function () {17 return this._builtins[name];18 };19 }20 var setter_name = builtin.setter_name || "set_" + name;21 builtin._get_setter_name = function () {return setter_name; };22 if (_.isFunction(builtin.setter)) {23 proto[setter_name] = function () {24 return builtin.setter.apply(this, ([this._builtins[name]]).concat(_.toArray(arguments)));25 };26 } else if (builtin.settable !== false) {27 proto[setter_name] = function (set_to) {28 this._builtins[name] = set_to;29 };30 }31 var env_name = builtin.env_name || name;32 builtin._get_env_name = function () { return env_name; };33 });34 };35 ist.install_instance_builtins = function (obj, options, constructor) {36 var builtins = constructor.builtins;37 obj._builtins = obj._builtins || {};38 _.each(builtins, function (builtin, name) {39 var setter_name = builtin.setter_name || "set_" + name;40 if (_.isFunction(builtin.start_with)) {41 obj._builtins[name] = builtin.start_with.call(obj);42 }43 if (builtin.settable === false) {44 if (!_.isFunction(builtin.start_with)) {45 if (options && _.has(options, name)) {46 obj._builtins[name] = options[name];47 } else if (_.isFunction(builtin["default"])) {48 obj._builtins[name] = builtin["default"].call(obj);49 }50 }51 } else {52 if (options && _.has(options, name)) {53 obj[setter_name](options[name]);54 } else if (_.isFunction(builtin["default"])) {55 obj[setter_name](builtin["default"].call(obj));56 }57 }58 });59 };60 ist.unset_instance_builtins = function(obj, constructor) {61 var builtins = constructor.builtins;62 _.each(builtins, function (builtin, name) {63 if (_.isFunction(builtin.destroy)) {64 builtin.destroy.call(obj, obj._builtins[name]);65 }66 delete obj._builtins[name];67 });68 };69 var default_hash = function () {70 var rv = "",71 i;72 for (i = 0; i < arguments.length; i += 1) {73 rv += arguments[i].toString();74 }75 return rv;76 };77 var default_equals = function (args1, args2) {78 var i;79 if (args1.length === args2.length) {80 for (i = 0; i < args1.length; i += 1) {81 var arg1 = args1[i],82 arg2 = args2[i];83 if (arg1 !== arg2) {84 return false;85 }86 }87 return true;88 } else {89 return false;90 }91 };...

Full Screen

Full Screen

registerGetters.js

Source:registerGetters.js Github

copy

Full Screen

1import chalk from 'chalk';2import getAPIURLComponent from "./getAPIURLComponent";3import getAPIContext from "./getAPIContext";4import formatAPIError from "../lib/formatAPIError";5import validate from "../validation/index.js";6import getOutput from "./getOutput";7export default (express, getters = [], context = {}) => {8 const { app } = express;9 if (app) {10 for (const [getter_name, getter_options] of getters) {11 app.get(12 `/api/_getters/${getAPIURLComponent(getter_name)}`,13 async (req, res) => {14 const getter_context = await getAPIContext({ req, res }, context);15 const { query } = req;16 const input = query?.input ? JSON.parse(query?.input) : null;17 const output = query?.output ? JSON.parse(query?.output) : null;18 const authorized = getter_options?.authorized;19 const get = getter_options?.get;20 let validationErrors = [];21 if (getter_options?.input) {22 validationErrors = await validate.inputWithSchema(input, getter_options.input);23 }24 if (validationErrors.length > 0) {25 console.log('');26 console.log(`Input validation for getter "${getter_name}" failed with the following errors:\n`);27 validationErrors.forEach((validationError, index) => {28 console.log(`#${index + 1}. ${validationError}`);29 });30 return res.status(400).send(31 JSON.stringify({32 errors: validationErrors.map((error) => {33 return formatAPIError(new Error(error, "validation"));34 }),35 })36 );37 }38 if (authorized && typeof authorized === 'function') {39 const isAuthorized = await authorized(input, getter_context);40 if (!isAuthorized) {41 return res.status(403).send(42 JSON.stringify({43 errors: [44 formatAPIError(new Error(`Not authorized to access ${getter_name}.`, "authorized")),45 ],46 })47 );48 }49 }50 if (get && typeof get === "function") {51 try {52 const data = (await get(input, getter_context)) || {};53 const response = output ? getOutput(data, output) : data;54 return res.send(JSON.stringify(response || {}));55 } catch (exception) {56 console.log(exception);57 return res.status(500).send(58 JSON.stringify({59 errors: [formatAPIError(exception, "server")],60 })61 );62 }63 }64 res.status(200).send(JSON.stringify({ errors: [] }));65 }66 );67 }68 }...

Full Screen

Full Screen

model.js

Source:model.js Github

copy

Full Screen

1var model = {}2model.Model = function() {3 this.dirty = {};4}5model.Model.prototype.setter_name = function(field){6 return _.sprintf("_%s_setter" , field);7};8model.Model.prototype.getter_name = function(field){9 return _.sprintf("_%s_getter", field);10};11model.Model.prototype.set = function(field, value){12 if (this.setter_name(field) in this){13 this[this.setter_name(field)](value);14 }else{15 this[field] = value;16 }17 this.dirty[field] = true;18};19model.Model.prototype.get = function(field){ 20 if (this.getter_name(field) in this){21 return this[this.getter_name(field)](field);22 }else{23 return this[field];24 }25};26model.Model.prototype.to_dict = function(){27 var data = {}28 var obj = this;29 _.each(this.fields, 30 function(f){31 data[f] = obj.get(f);32 });33 return data;34}35model.Model.prototype.update = function(data){36 var obj = this;37 _.each(this.fields,38 function(f){39 if (f in data){40 obj.set(f, data[f]);41 }42 });43}44model.Model.prototype.serialize = function(){45 return JSON.stringify(this.to_dict());46}47model.Model.prototype.deserialize = function(str){48 var data = JSON.parse(str);49 this.update(data);50}51model.Model.prototype.field_id = function(fld){52 if (!fld){53 return this.get('id');54 }else{55 return this.get('id') + "-" + fld;56 }57}58model.Model.prototype.field_el = function(fld){59 if (!fld){60 return this.el;61 }else{62 return $("#" + this.field_id(fld), this.el);63 }64}65model.Model.prototype.render_function = function(field){66 var obj = this;67 if ("render_" + field in this){68 return function(){obj["render_" + field]()};69 }else{70 return function() {obj.render_field(field);};71 }72}73model.Model.prototype.render_field = function(field){74 $("#" + this.field_id(field), this.el).html(this.get(field));75};76model.Model.prototype.render = function(isroot){77 if (!this.el){78 this.el = $(this.template(this.to_dict()));79 this.hook_events()80 }81 var obj = this;82 _.each(this.fields, function(f){83 if (obj.dirty[f]){84 obj.render_function(f).call(obj);85 delete obj.dirty[f];86 }87 });88};89model.Model.prototype.template = function(){90};91model.Model.prototype.hook_events = function(){...

Full Screen

Full Screen

mutations.js

Source:mutations.js Github

copy

Full Screen

1import { gql } from "@apollo/client/core";2export const CREATE_CHATBOX_MUTATION = gql`3 mutation createChatBox(4 $name1: String!,5 $name2: String!6 ) {7 createChatBox(8 name1: $name1,9 name2: $name210 ) {11 name12 messages {13 sender {14 name15 }16 body17 }18 }19 }20`21export const CREATE_MESSAGE_MUTATION = gql`22 mutation createMessage(23 $sender_name: String!,24 $getter_name: String!, 25 $body: String!26 ) {27 createMessage(28 sender_name: $sender_name, 29 getter_name: $getter_name, 30 body: $body31 ) {32 sender {33 name34 }35 body36 }37 }38`39export const DELETE_MESSAGE_MUTATION = gql`40 mutation deleteMessage {41 deleteMessage42 }...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest 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