Best JavaScript code snippet using cypress
Widget.js
Source:Widget.js
1///////////////////////////////////////////////////////////////////////////2// Copyright © 2015 Softwhere Solutions 3// All Rights Reserved.4//5// Licensed under the Apache License Version 2.0 (the "License");6// you may not use this file except in compliance with the License.7// You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing, software12// distributed under the License is distributed on an "AS IS" BASIS,13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14// See the License for the specific language governing permissions and15// limitations under the License.16///////////////////////////////////////////////////////////////////////////17/*global console, define, dojo, FileReader */18define(['dojo/_base/declare',19 'jimu/BaseWidget',20 'dijit/_WidgetsInTemplateMixin',21 'dojo/_base/lang',22 'dojo/_base/array',23 'dojo/_base/html',24 'dojo/dom-attr',25 'dojo/query',26 'dojo/on',27 'dojo/topic',28 'dojo/string',29 'dojo/json',30 'dojo/Deferred',31 'dojo/promise/all',32 "./LayerLoader",33 'esri/geometry/Extent',34 35 'esri/graphic',36 'esri/layers/GraphicsLayer',37 'esri/layers/FeatureLayer',38 'esri/layers/ImageParameters',39 'esri/layers/ArcGISDynamicMapServiceLayer',40 'esri/layers/ArcGISTiledMapServiceLayer',41 "esri/layers/WFSLayer",42 "esri/layers/WMSLayer",43 "esri/layers/WMTSLayer",44 'jimu/ConfigManager',45 'jimu/MapManager',46 'jimu/dijit/Popup',47 'jimu/dijit/Message',48 'jimu/LayerInfos/LayerInfos',49 './SimpleTable',50 'dijit/form/TextBox',51 'esri/map'52 ],53 function (declare,54 BaseWidget,55 _WidgetsInTemplateMixin,56 lang,57 array,58 html,59 domAttr,60 query,61 on,62 topic,63 string,64 JSON,65 Deferred,66 all,67 LayerLoader,68 Extent,69 Graphic,70 GraphicsLayer,71 FeatureLayer,72 ImageParameters,73 ArcGISDynamicMapServiceLayer,74 ArcGISTiledMapServiceLayer,75 WFSLayer, 76 WMSLayer, 77 WMTSLayer,78 ConfigManager,79 MapManager,80 Popup,81 Message,82 LayerInfos,83 Table,84 TextBox) {85 //To create a widget, you need to derive from BaseWidget.86 return declare([BaseWidget, _WidgetsInTemplateMixin], {87 // Custom widget code goes here88 89 baseClass: 'jimu-widget-savesession',90 // name of sessions string in local storage91 storageKey: "sessions",92 93 // the saved sessions94 sessions: [],95 wabWidget: null,96 _dfd: null,97 postCreate: function () {98 this.inherited(arguments);99 // setup save to file100 this.saveToFileForm.action = this.config.saveToFileUrl;101 this.saveToFileName.value = this.config.defaultFileName;102 this.loadSavedSessionsFromStorage();103 this.initSavedSessionUI();104 this.initNewSessionUI();105 this.refreshLoadFileUI();106 //console.log('SaveSession :: postCreate :: completed');107 },108 startup: function () {109 this.inherited(arguments);110 //console.log('SaveSession :: startup');111 },112 onOpen: function () {113 //console.log('SaveSession :: onOpen');114 },115 /**116 * create the table of saved sessions117 */118 initSavedSessionUI: function () {119 var tableSettings = {120 autoHeight: true,121 fields: [122 {123 "name": "name",124 "title": "Session",125 "type": "text",126 "class": "session-name",127 "unique": true,128 "hidden": false,129 "editable": true130 },131 {132 "name": "actions",133 "title": "Actions",134 "type": "actions",135 "class": "actions",136 "actions": ['load', 'download', 'edit', 'up', 'down', 'delete']137 }138 ],139 selectable: false140 };141 this.sessionTable = new Table(tableSettings);142 this.sessionTable.placeAt(this.savedSessionContainer);143 this.sessionTable.startup();144 // listend for events on session table145 this.own(on(this.sessionTable, 'row-delete', lang.hitch(this, 'onSessionTableChanged')));146 this.own(on(this.sessionTable, 'row-up', lang.hitch(this, 'onSessionTableChanged')));147 this.own(on(this.sessionTable, 'row-down', lang.hitch(this, 'onSessionTableChanged')));148 this.own(on(this.sessionTable, 'row-edit', lang.hitch(this, 'onSessionTableChanged')));149 this.own(on(this.sessionTable, 'actions-load', lang.hitch(this, 'onLoadSessionClicked')));150 this.own(on(this.sessionTable, 'row-dblclick', lang.hitch(this, 'onLoadSessionClicked')));151 this.own(on(this.sessionTable, 'actions-download', lang.hitch(this, 'onSaveItemToFileClicked')));152 this.sessionTable.addRows(this.sessions);153 //console.log('SaveSession :: initSavedSessionUI :: session table created');154 },155 /**156 * reload the table with the saved sessions157 */158 refreshSavedSessionUI: function () {159 this.sessionTable.clear();160 this.sessionTable.addRows(this.sessions);161 //console.log('SaveSession :: refreshSavedSessionUI :: session table refreshed');162 },163 /**164 * set up the UI for New Session165 */166 initNewSessionUI: function () {167 this.refreshNewSessionUI();168 this.own(this.sessionNameTextBox.on('change', lang.hitch(this, 'refreshNewSessionUI')));169 this.own(this.sessionNameTextBox.on('keypress', lang.hitch(this, 'onKeyPressed')));170 //console.log('SaveSession :: initNewSessionUI :: end');171 },172 /**173 * enable the save file link when there are sessions174 */175 refreshLoadFileUI: function () {176 var sessionString = "",177 hasSessions = false;178 hasSessions = this.sessions && this.sessions.length > 0;179 if (!hasSessions) {180 domAttr.set(this.saveToFileButton, "disabled", "true");181 html.addClass(this.saveToFileButton, "jimu-state-disabled");182 //console.log('SaveSession :: refreshLoadFileUI :: save to file button disabled');183 } else {184 domAttr.remove(this.saveToFileButton, "disabled");185 html.removeClass(this.saveToFileButton, "jimu-state-disabled");186 //console.log('SaveSession :: refreshLoadFileUI :: save to file button enabled');187 }188 // use a data url to save the file, if not using a server url189 // if useServerToDownloadFile, use a form post to a service instead190 if (!this.config.useServerToDownloadFile) {191 // also set the save to link if has sessions192 // this uses data url to prompt user to download193 if (hasSessions) {194 sessionString = JSON.stringify(this.sessions);195 // must convert special chars to url encoding196 sessionString = encodeURIComponent(sessionString);197 domAttr.set(this.saveToFileButton, "href", "data:application/octet-stream," + sessionString);198 domAttr.set(this.saveToFileButton, "download", this.config.fileNameForAllSessions);199 //console.log('SaveSession :: refreshLoadFileUI :: data url set on saveToFileButton');200 }201 }202 },203 /**204 * when a key is pressed, check the session name205 * @param {Object} e event args206 */207 onKeyPressed: function (e) {208 if (e.keyCode === dojo.keys.ENTER) {209 this.onSaveButtonClicked();210 }211 setTimeout(lang.hitch(this, 'refreshNewSessionUI'), 0);212 //console.log('SaveSession :: onKeyPressed :: end');213 },214 /**215 * enable the save button when a valid entry is in textbox216 */217 refreshNewSessionUI: function () {218 var sessionName = "",219 isValid = false;220 sessionName = this.sessionNameTextBox.get("value");221 // must have a valid session name to enable save222 isValid = this.isValidSessionName(sessionName);223 if (!isValid) {224 domAttr.set(this.saveButton, "disabled", "true");225 html.addClass(this.saveButton, "jimu-state-disabled");226 //console.log('SaveSession :: refreshNewSessionUI :: save button disabled');227 } else {228 domAttr.remove(this.saveButton, "disabled");229 html.removeClass(this.saveButton, "jimu-state-disabled");230 //console.log('SaveSession :: refreshNewSessionUI :: save button enabled');231 }232 this.inputText.innerHTML = this.getMesageForSessionName(sessionName);233 //console.log('SaveSession :: refreshNewSessionUI :: end');234 },235 /**236 * checks if the given name is valid - has text and is not already taken237 * @param {String} sessionName name for the session238 * @returns {Boolean} true if the given session name is not already entered239 */240 isValidSessionName: function (name) {241 if (!name) {242 return false;243 }244 // check for duplicates245 var hasSameName = array.some(this.sessions, function (session) {246 return session.name === name;247 }, this);248 return !hasSameName;249 },250 /**251 * checks if the given name is valid - has text and is not already taken252 * @param {String} sessionName name for the session253 * @returns {String} true if the given session name is not already entered254 */255 getUniqueSessionName: function (name, idx) {256 idx = idx || 0; // default to 0257 idx += 1;258 var newName = name + " " + String(idx);259 if (!this.isValidSessionName(newName)) {260 newName = this.getUniqueSessionName(name, idx);261 }262 return newName;263 },264 /**265 * returns input text for session name266 * @param {String} sessionName name for the session267 * @returns {String} a help message268 */269 getMesageForSessionName: function (name) {270 var text = "",271 hasSameName = false;272 if (!name) {273 text = "Enter the name for the session";274 }275 // check for duplicates276 hasSameName = array.some(this.sessions, function (session) {277 return session.name === name;278 }, this);279 if (hasSameName) {280 text = "Enter a unique name for the session";281 }282 return text;283 },284 /**285 * when the save button is clicked, add the session to local storage286 */287 onSaveButtonClicked: function () {288 //console.log('SaveSession :: onSaveButtonClicked :: begin');289 var session,290 sessionName = "";291 sessionName = this.sessionNameTextBox.get("value");292 if (!this.isValidSessionName(sessionName)) {293 //console.log('SaveSession :: onSaveButtonClicked :: invalid sesion name = ', sessionName);294 return;295 }296 session = this.getSettingsForCurrentMap();297 session.name = sessionName;298 this.sessions.push(session);299 //console.log("SaveSession :: onSaveButtonClicked :: added session = ", session);300 this.storeSessions();301 this.sessionTable.addRow(session);302 this.refreshLoadFileUI();303 this.refreshNewSessionUI();304 //console.log('SaveSession :: onSaveButtonClicked :: end');305 },306 /**307 * get the sessions from the table and store them308 */309 onSessionTableChanged: function (e) {310 //console.log('SaveSession :: onSessionTableChanged :: begin');311 // store changed sessions312 this.sessions = this.sessionTable.getItems();313 this.storeSessions();314 // and update ui315 this.refreshLoadFileUI();316 this.refreshNewSessionUI();317 //console.log('SaveSession :: onSessionTableChanged :: session stored');318 },319 /**320 * Load the session when clicked in Table321 * @param {Object} e the event args - item = session322 */323 onLoadSessionClicked: function (e) {324 var session = e.item;325 //console.log('SaveSession :: onLoadSessionClicked :: session = ', session);326 this.loadSession(session);327 },328 /**329 * prompt to upload file330 * @param {Object} e the event args 331 */332 onLoadFromFileButtonClicked: function (e) {333 var popup = new Popup({334 titleLabel: "Load sessions from file",335 autoHeight: true,336 content: "Choose the file to load: <input type='file' id='file-to-load' name='file' enctype='multipart/form-data' />",337 container: 'main-page',338 width: 400,339 height: 200,340 buttons: [{341 label: "Ok",342 key: dojo.keys.ENTER,343 onClick: lang.hitch(this, function () {344 //console.log('SaveSession :: onLoadFromFile :: ok');345 var fileInput,346 fileName;347 // get file from input348 fileInput = query('#file-to-load', popup.domNode)[0];349 fileName = fileInput.files[0];350 popup.close();351 this.loadSavedSessionsFromFile(fileName);352 })353 }, {354 label: "Cancel",355 key: dojo.keys.ESCAPE,356 onClick: lang.hitch(this, function () {357 //console.log('SaveSession :: onLoadFromFile :: canceled');358 popup.close();359 })360 }],361 onClose: lang.hitch(this, function () {362 //console.log('SaveSession :: onLoadFromFile :: closed');363 })364 });365 //console.log('SaveSession :: onLoadFromFileButtonClicked :: ');366 },367 /**368 * save sessions to file369 * @param {Object} e the event args 370 */371 onSaveToFileButtonClicked: function (e) {372 if (!this.config.useServerToDownloadFile) {373 // skipping since there is no url to submit to374 //console.log('SaveSession :: onSaveToFileButtonClicked :: saveToFileForm submit canceled.');375 return;376 }377 var sessionString = JSON.stringify(this.sessions);378 // update form values379 this.saveToFileName.value = this.config.fileNameForAllSessions;380 this.saveToFileContent.value = sessionString;381 // trigger the post to server side382 //this.saveToFileForm.submit();383 //console.log('SaveSession :: onSaveToFileButtonClicked :: end');384 },385 /**386 * save the single item to file387 * @param {Object} e the event args 388 */389 onSaveItemToFileClicked: function (e) {390 var sessionString = "",391 fileName = "",392 sessions = [];393 fileName = string.substitute(this.config.fileNameTplForSession, e.item);394 sessions.push(e.item);395 sessionString = JSON.stringify(sessions);396 // update form values397 this.saveToFileName.value = fileName;398 this.saveToFileContent.value = sessionString;399 // trigger the post to server side400 this.saveToFileForm.submit();401 //console.log('SaveSession :: onSaveItemToFileClicked :: end');402 },403 /**404 * load the session definitions from the given text file405 * @param {Object} file reference to text file to load406 */407 loadSavedSessionsFromFile: function (file) {408 //console.log('SaveSession :: loadSavedSessionsFromFile :: begin for file = ', file);409 var sessionsString = "",410 sessionsToLoad = null,411 reader,412 msg,413 loadedCount = 0,414 me = this;415 reader = new FileReader();416 // when the file is loaded417 reader.onload = function () {418 var sessionsString = reader.result;419 if (!sessionsString) {420 console.warn("SaveSession :: loadSavedSessionsFromFile : no sessions to load");421 msg = new Message({422 message: "No sessions found in the file.",423 type: 'message'424 });425 return;426 }427 sessionsToLoad = JSON.parse(sessionsString);428 //console.log("SaveSession :: loadSavedSessionsFromFile : sessions found ", sessionsToLoad);429 array.forEach(sessionsToLoad, function (sessionToLoad) {430 var isValid = me.isValidSessionName(sessionToLoad.name);431 if (!isValid) {432 // fix the session name433 sessionToLoad.name = me.getUniqueSessionName(sessionToLoad.name);434 //console.log("SaveSession :: loadSavedSessionsFromFile :: session name changed to " + sessionToLoad.name);435 }436 // refresh tabl437 this.sessions.push(sessionToLoad);438 this.sessionTable.addRow(sessionToLoad);439 loadedCount += 1;440 }, me);441 // do not call refresh ui since session table will trigger change event442 me.storeSessions();443 me.refreshLoadFileUI();444 msg = new Message({445 message: String(loadedCount) + " sessions loaded from the file.",446 type: 'message'447 });448 //console.log('SaveSession :: loadSavedSessionsFromFile :: end for file = ', file);449 };450 // starting reading, and continue when load event fired451 reader.readAsText(file);452 },453 /**454 * Apply the settings from the given session to the current map455 * @param {Object} sessionToLoad a session456 */457 loadSession: function (sessionToLoad) {458 var onMapChanged,459 extentToLoad;460 if (sessionToLoad.webmapId && sessionToLoad.webmapId !== this.map.itemId) {461 //console.log('SaveSession :: loadSession :: changing webmap = ', sessionToLoad.webmapId);462 onMapChanged = topic.subscribe("mapChanged", lang.hitch(this, function (newMap) {463 //console.log('SaveSession :: loadSession :: map changed from ', this.map.itemId, ' to ', newMap.itemId);464 // update map reference here465 // since this.map still refers to old map?466 // ConfigManager has not recreated widget with new map yet467 this.map = newMap;468 // do not listen any more469 onMapChanged.remove();470 // load the rest of the session471 this.loadSession(sessionToLoad);472 }));473 ConfigManager.getInstance()._onMapChanged({474 "itemId": sessionToLoad.webmapId475 });476 // do not continue until webmap is changed477 return;478 }479 // zoom the map480 if (sessionToLoad.extent) {481 extentToLoad = new Extent(sessionToLoad.extent);482 this.map.setExtent(extentToLoad).then(function () {483 //console.log('SaveSession :: loadSession :: new extent = ', extentToLoad);484 }, function () {485 var msg = new Message({486 message: string.substitute("An error occurred zooming to the ${name} map.", sessionToLoad),487 type: 'error'488 });489 });490 }491 // load the saved graphics492 this.setGraphicsOnCurrentMap(sessionToLoad.graphics);493 // toggle layers494 if (sessionToLoad.layers) {495 this.setLayersOnMap(sessionToLoad.layers);496 }497 //console.log('SaveSession :: loadSession :: session = ', sessionToLoad);498 },499 /**500 * apply settings to layers501 * @param {Array} array of layer settings to apply to map502 */503 setLayersOnMap: function (settings) {504 var propName = "",505 layerSettings,506 layer,507 addGraphicsToLayer;508 array.forEach(settings, function (layerSettings) {509 layer = this.map.getLayer(layerSettings.id);510 if (!layer) {511 //console.log('SaveSession :: setLayersOnMap :: no layer found with id = ', propName);512 layer = this.addLayerToMap(layerSettings);513 // exit here? or re-apply settings 514 return;515 }516 // set visible517 if (layer.setVisibility) {518 layer.setVisibility(layerSettings.isVisible);519 //console.log('SaveSession :: loadSession :: set visibility = ', layerSettings.isVisible, ' for layer : id=', layer.id);520 }521 if (layerSettings.visibleLayers && layer.setVisibleLayers) {522 layer.setVisibleLayers(layerSettings.visibleLayers);523 }524 //console.log('SaveSession :: loadSession :: setLayersOnMap completed for layer = ', layer.id);525 }, this);526 // fire refresh event 527 LayerInfos.getInstance(this.map, this.map.itemInfo).then(function (layerInfosObject) { // fire change event to trigger update528 on.emit(layerInfosObject, "updated");529 //layerInfosObject.onlayerInfosChanged();530 });531 },532 /**533 * create a new map layer with the given settings534 * @param {Object} layerSettings settings for the layer535 * @return {Object} layer oject536 */537 addLayerToMap: function (layerSettings) {538 539 var loader = new LayerLoader();540 var id = loader._generateLayerId();541 var dfd= new Deferred();542 //console.log('SaveSession :: addLayerToMap :: adding layer = ', layerSettings);543 var layer,544 options;545 switch (layerSettings.type) {546 case "ArcGISDynamicMapServiceLayer":547 options = lang.clone(layerSettings.options);548 options.imageParameters = new ImageParameters();549 lang.mixin(options.imageParameters, layerSettings.options.imageParameters);550 layer = new ArcGISDynamicMapServiceLayer(layerSettings.url, options);551 //console.log('SaveSession :: addLayerToMap :: created ArcGISDynamicMapServiceLayer layer = ', layer);552 break;553 case "FeatureLayer":554 layer = new FeatureLayer(layerSettings.url, layerSettings.options);555 //console.log('SaveSession :: addLayerToMap :: created Feature layer = ', layer);556 break;557 case "ArcGISTiledMapServiceLayer":558 layer = new ArcGISTiledMapServiceLayer(layerSettings.url, layerSettings.options);559 //console.log('SaveSession :: addLayerToMap :: created ArcGISTiledMapServiceLayer layer = ', layer);560 break;561 case "WMSLayer":562 var layerVisible = [];563 564 565 for (var i = 0; i < layerSettings.visibleLayers.length; i++) {566 567 568 //console.log(layerSettings.visibleLayers[i]);569 //data_table += "<tr> <td> " + data.features[i].attributes.source + "</td> <td> " + data.features[i].attributes.average_family_size + "</td><td>" + data.features[i].attributes.source + "</td></tr>";570 layerVisible.push(layerSettings.visibleLayers[i]);571 //chartjsLabel.push(data.features[i].attributes.source);572 //chartjsData.push(data.features[i].attributes.average_family_size); 573 }574 //console.log(layerVisible);575 layer = new WMSLayer(layerSettings.url, {576 format: "png",577 578 579 visibleLayers: layerVisible580 });581 582 /* loader._waitForLayer(layer).then(function(lyr) {583 584 585 loader._setWMSVisibleLayers(lyr);586 587 lyr.xtnAddData = true; */588 //map.addLayer(layer);589 /* dfd.resolve(lyr);590 }).otherwise(function(error) {591 592 dfd.reject(error);593 }); */594 //console.log('SaveSession :: addLayerToMap :: created WMSLayer layer = ', layer);595 break;596 597 default:598 //console.log('SaveSession :: addLayerToMap :: unsupported layer type = ', layerSettings.type);599 break;600 }601 if (layerSettings.name) {602 layer.name = layerSettings.name;603 }604 // The bottom most layer has an index of 0.605 this.map.addLayer(layer, layerSettings.order);606 //console.log('SaveSession :: addLayerToMap :: created layer for ', layer.id, ' using settings = ', layerSettings);607 return layer;608 },609 /**610 * returns the session object for the current map611 * @returns {Object} map settings for session612 */613 getSettingsForCurrentMap: function () {614 var settings = {615 name: "",616 webmapId: "",617 extent: null,618 layers: [],619 graphics: []620 };621 settings.extent = this.map.extent;622 settings.webmapId = this.map.itemId;623 settings.graphics = this.getGraphicsForCurrentMap();624 // have to use async to get layers625 this.getLayerSettingsForCurrentMap().then(function (layerSettings) {626 settings.layers = layerSettings;627 //console.log('SaveSession :: getSettingsForCurrentMap :: layerSettings completed = ', layerSettings);628 }, function (err) {629 var msg = new Message({630 message: string.substitute("An error getting the layers from the current map."),631 type: 'error'632 });633 });634 return settings;635 },636 /**637 * async return the settings for the current layers on the map638 * @returns {Array} returns an array of layers defs to save639 */640 getLayerSettingsForCurrentMap: function () {641 var def = new Deferred();642 this.getLayerObjectsFromMap().then(lang.hitch(this, function (result) {643 //console.log('SaveSession :: getLayerSettingsForCurrentMap :: layersObects = ', result);644 try {645 var settings = [],646 layerSettings,647 maxIndex = result.layerObjects.length;648 array.forEach(result.layerObjects, function (layer, idx) {649 // layer settings uses layerId as property name650 layerSettings = this.getSettingsForLayer(layer);651 layerSettings.order = maxIndex - idx; // The bottom most layer has an index of 0. so reverse order652 settings.push(layerSettings);653 }, this);654 def.resolve(settings);655 } catch (err) {656 //console.error('SaveSession :: getLayerSettingsForCurrentMap :: error getting layersObects = ', err);657 def.reject(err);658 }659 }), lang.hitch(this, function (err) {660 //console.error('SaveSession :: getLayerSettingsForCurrentMap :: error getting layersObects = ', err);661 def.reject(err);662 }));663 return def.promise;664 },665 /**666 * return the settings to store for the given layer667 * @param {esri.layers.Layer} layer the layer to get the settings for668 * @returns {Object} the settings object to store for the given layer669 */670 getSettingsForLayer: function (layer) {671 var layerSettings = {672 id: layer.id,673 name: layer.name,674 type: "",675 isVisible: layer.visible,676 visibleLayers: layer.visibleLayers || null,677 url: layer.url,678 options: null679 };680 layerSettings.type = this.getLayerType(layer);681 switch (layerSettings.type) {682 case "ArcGISDynamicMapServiceLayer":683 layerSettings.options = this.getOptionsForDynamicLayer(layer);684 break;685 case "FeatureLayer":686 layerSettings.options = this.getOptionsForFeatureLayer(layer);687 //console.log('SaveSession :: getSettingsForLayer :: added options for feature layer = ', layerSettings);688 break;689 case "ArcGISTiledMapServiceLayer":690 layerSettings.options = this.getOptionsForTiledLayer(layer);691 //console.log('SaveSession :: getSettingsForLayer :: added options for tiled layer = ', layerSettings);692 break;693 case "WMSLayer":694 layerSettings.options = this.getOptionsForWMSLayer(layer);695 //console.log('SaveSession :: getSettingsForLayer :: added options for WMS layer = ', layerSettings);696 break;697 default:698 //console.log('SaveSession :: getSettingsForLayer :: no options for layer type = ', layerSettings.type);699 break;700 }701 //console.log('SaveSession :: getSettingsForCurrentMap :: settings ', layerSettings, ' added for layer = ', layer.id);702 return layerSettings;703 },704 /**705 * return the options object to create the given layer706 * @param {esri.layers.ArcGISDynamicMapServiceLayer} layer the ArcGISDynamicMapServiceLayer 707 * @returns {Object} Object with properties for the ArcGISDynamicMapServiceLayer constructor708 */709 getOptionsForDynamicLayer: function (layer) {710 //console.log('0');711 var ip,712 options = {713 id: layer.id,714 imageParameters: null,715 opacity: layer.opacity,716 refreshInterval: layer.refreshInterval,717 visible: layer.visible718 };719 if (layer.imageFormat) {720 ip = {721 format: layer.imageFormat,722 dpi: layer.dpi723 };724 options.imageParameters = ip;725 }726 //console.log('SaveSession :: getOptionsForDynamicLayer :: options = ', options, ' for layer = ', layer.id);727 return options;728 },729 /**730 * return the options object to create the given layer731 * @param {esri.layers.FeatureLayer} layer the FeatureLayer 732 * @returns {Object} Object with properties for the FeatureLayer constructor733 */734 getOptionsForFeatureLayer: function (layer) {735 //console.log('1');736 var options = {737 id: layer.id,738 mode: FeatureLayer.MODE_ONDEMAND,739 outFields: ["*"],740 opacity: layer.opacity,741 refreshInterval: layer.refreshInterval,742 visible: layer.visible743 };744 // TODO: get mode?745 //console.log('SaveSession :: getOptionsForFeatureLayer :: options = ', options, ' for layer = ', layer.id);746 return options;747 },748 /**749 * return the options object to create the given layer750 * @param {esri.layers.ArcGISTiledMapServiceLayer} layer the Tiled layer 751 * @returns {Object} Object with properties for the ArcGISTiledMapServiceLayer constructor752 */753 getOptionsForTiledLayer: function (layer) {754//console.log('3');755 var options = {756 id: layer.id,757 opacity: layer.opacity,758 refreshInterval: layer.refreshInterval,759 visible: layer.visible760 };761 //console.log('SaveSession :: getOptionsForTiledLayer :: options = ', options, ' for layer = ', layer.id);762 return options;763 },764getOptionsForWMSLayer: function (layer) {765//console.log('4');766 var options = {767 id: layer.id,768 format: "png",769 //visible: layer.visible770 };771 //console.log('SaveSession :: getOptionsForWMSLayer :: options = ', options, ' for layer = ', layer.id);772 return options;773 },774 /**775 * return all the settings for the current graphic layers776 * @returns {Array} array of settings objects for each graphic layer777 */778 getGraphicsForCurrentMap: function () {779 var settings = [],780 graphicLayer,781 layerSettings;782 // always add the default graphics layer783 layerSettings = this.getSettingsFromGraphicsLayer(this.map.graphics);784 settings.push(layerSettings);785 // save the graphics for other layers786 array.forEach(this.map.graphicsLayerIds, function (layerId) {787 graphicLayer = this.map.getLayer(layerId);788 if (graphicLayer.graphics.length > 0) {789 // if there are graphics then save the settings790 layerSettings = this.getSettingsFromGraphicsLayer(graphicLayer);791 settings.push(layerSettings);792 }793 }, this);794 //console.log('SaveSession :: getGraphicsForCurrentMap :: settings added for graphics = ', settings);795 return settings;796 },797 /**798 * create settings object from the given graphics Layer799 * @param {GraphicLayer} graphicLayer a graphics layer800 * @returns {Object} the settings to store for the graphics layer801 */802 getSettingsFromGraphicsLayer: function (graphicLayer) {803 var settings = {804 id: graphicLayer.id,805 graphics: []806 };807 // set the graphics from the layer808 array.forEach(graphicLayer.graphics, function (g) {809 settings.graphics.push(g.toJson());810 }, this);811 //console.log('SaveSession :: getSettingsFromGraphicsLayer :: settings ', settings, ' added for graphicLayer = ', graphicLayer);812 return settings;813 },814 /** 815 * add the graphics defined in the settings to the current map816 * @param {Object} settings = object with property for each graphic layer817 */818 setGraphicsOnCurrentMap: function (settings) {819 var propName = "",820 settingsForLayer,821 graphicsLayer,822 addGraphicsToLayer;823 // helper function to add all graphics defined in the settings to the given graphics layer824 addGraphicsToLayer = function (graphicsLayer, settingsForLayer) {825 // add to default graphics layer826 array.forEach(settingsForLayer.graphics, function (g) {827 var graphic = new Graphic(g);828 graphicsLayer.add(graphic);829 }, this);830 };831 array.forEach(settings, function (settingsForLayer, i) {832 if (settingsForLayer.id === "map_graphics") {833 // already exists by default so add graphics834 addGraphicsToLayer(this.map.graphics, settingsForLayer);835 } else {836 // add a new layer837 graphicsLayer = new GraphicsLayer({838 id: settingsForLayer.id839 });840 // add the graphics layer at the index - The bottom most layer has an index of 0.841 //var idx = i - 1; // adjust to account for default map graphics at first index in settings842 // adds the graphiclayers on top of other layers, since index not specified843 this.map.addLayer(graphicsLayer);844 addGraphicsToLayer(graphicsLayer, settingsForLayer);845 }846 }, this);847 //console.log("SaveSession :: setGraphicsOnCurrentMap :: graphics added to the map");848 },849 clearAllGraphicsOnMap: function () {850 // clear the default layer851 this.map.graphics.clear();852 // remove the other graphics layers 853 array.forEach(this.map.graphicsLayerIds, function (layerId) {854 var layer = this.map.getLayer(layerId);855 this.map.removeLayer(layer);856 }, this);857 //console.log("SaveSession :: clearAllGraphicsOnMap :: graphics removed from the map");858 },859 /**860 * save the current sessions to local storage861 */862 storeSessions: function () {863 var stringToStore = JSON.stringify(this.sessions);864 localStorage.setItem(this.storageKey, stringToStore);865 //console.log("SaveSession :: storeSessions :: completed");866 },867 /**868 * read the saved sessions from storage869 */870 loadSavedSessionsFromStorage: function () {871 var storedString = "",872 storedSessions = null;873 storedString = localStorage.getItem("sessions");874 if (!storedString) {875 //console.log("SaveSession :: loadSavedSessionsFromStorage : no stored sessions to load");876 return;877 }878 storedSessions = JSON.parse(storedString);879 //console.log("SaveSession :: loadSavedSessionsFromStorage : sessions found ", storedSessions);880 // replace to current sessions881 this.sessions = storedSessions;882 //console.log("SaveSession :: loadSavedSessionsFromStorage : end");883 },884 getLayerObjectsFromMap: function () {885 return LayerInfos.getInstance(this.map, this.map.itemInfo).then(function (layerInfosObject) {886 var layerInfos = [],887 defs = [];888 /*889 layerInfosObject.traversal(function (layerInfo) {890 layerInfos.push(layerInfo);891 });892 */893 layerInfos = layerInfosObject.getLayerInfoArray();894 defs = array.map(layerInfos, function (layerInfo) {895 return layerInfo.getLayerObject();896 });897 return all(defs).then(function (layerObjects) {898 var resultArray = [];899 array.forEach(layerObjects, function (layerObject, i) {900 layerObject.id = layerObject.id || layerInfos[i].id;901 resultArray.push(layerObject);902 });903 return {904 layerInfosObject: layerInfosObject,905 layerInfos: layerInfos,906 layerObjects: resultArray907 };908 });909 });910 },911 /**912 * returns the last part of the declaredClass for the given layer object913 * @param {esri.layers.Layer} layer the map layer object914 * @returns {String} the layer type915 */916 getLayerType: function (layer) {917 var layerTypeArray = [],918 layerType = "";919 if (!layer) {920 return "";921 }922 layerTypeArray = layer.declaredClass.split(".");923 layerType = layerTypeArray[layerTypeArray.length - 1];924 return layerType;925 }926 });...
home.js
Source:home.js
...31 mutations: {32 SET_TAG_VIEW_ARR: (state, tagViewArr) => {33 state.tagViewArr = tagViewArr;34 // Cookies.set('localTag', localTag);35 Storage.saveSession("tagViewArr", tagViewArr);36 },37 CLEAR_TAG_VIEW: (state) => {38 state.tagViewArr = [];39 Storage.saveSession("tagViewArr", null);40 },41 ADD_TAG_VIEW_ITEM: (state, compomentItem) => {42 if (state.tagViewArr.some(v => v.name === compomentItem.name)) return;43 if (state.tagViewArr.length < state.tagHoldNum - 1) {44 state.tagViewArr.push(compomentItem);45 } else {46 state.tagViewArr.unshift(compomentItem);47 }48 Storage.saveSession("tagViewArr", state.tagViewArr);49 },50 DEL_TAG_VIEW_ITEM: (state, compomentItem) => {51 for (const [i, v] of state.tagViewArr.entries()) {52 if (v.path === compomentItem.path || v.name === compomentItem.name) {53 state.tagViewArr.splice(i, 1);54 break;55 }56 }57 Storage.saveSession("tagViewArr", state.tagViewArr);58 },59 SET_LOCAL_TAG: (state, localTag) => {60 state.localTag = localTag;61 Storage.saveSession("localTag", localTag);62 },63 SET_LOCAL_ENUMS: (state, localEnums) => {64 state.localEnums = localEnums;65 console.log(typeof localEnums);66 Storage.saveSession("localEnums", localEnums);67 },68 SET_MAP_STYLE: (state, mapStyle) => {69 state.mapStyle = mapStyle;70 Storage.saveSession("mapStyle", mapStyle);71 },72 SET_AREA_MAP_BORDER: (state, areaMapBorder) => {73 state.areaMapBorder = areaMapBorder;74 Storage.saveSession("areaMapBorder", areaMapBorder);75 },76 SET_CAPTURE_PHOTO_ARR: (state, CapturePhotoArr) => {77 state.CapturePhotoArr = CapturePhotoArr;78 Storage.saveSession("CapturePhotoArr", CapturePhotoArr);79 },80 SET_RECOGNIZATION_ARR: (state, RecognizationArr) => {81 state.RecognizationArr = RecognizationArr;82 Storage.saveSession("RecognizationArr", RecognizationArr);83 },84 SET_GLOBAL_ALARM: (state, GlobalAlarm) => {85 state.GlobalAlarm = GlobalAlarm;86 Storage.saveSession("GlobalAlarm", GlobalAlarm);87 },88 SET_AUTHORIZATION: (state, Authorization) => {89 state.Authorization = Authorization;90 Storage.saveSession("Authorization", Authorization);91 },92 // SET_UserName: (state, username) => {93 // state.username = username;94 // Storage.saveSession("username", username);95 // },96 SET_PROJECT_UUID: (state, projectUuid) => {97 state.projectUuid = projectUuid;98 Storage.saveSession("projectUuid", projectUuid);99 },100 SET_PROJECT_LIST: (state, projectList) => {101 state.projectList = projectList;102 Storage.saveSession("projectList", projectList);103 },104 SET_ACCOUNT: (state, account) => {105 state.account = account;106 Storage.saveSession("account", account);107 },108 SET_ACCOUNT_NAME: (state, accountName) => {109 state.accountName = accountName;110 Storage.save("accountName", accountName);111 },112 SET_USERUUID: (state, userUuid) => {113 state.userUuid = userUuid;114 Storage.saveSession("userUuid", userUuid);115 },116 SET_PLAT_FORMLEVEL: (state, platformLevel) => {117 state.platformLevel = platformLevel;118 Storage.saveSession("platformLevel", platformLevel);119 },120 SET_ROUTER_DATA: (state, routerData) => {121 state.routerData = routerData;122 Storage.saveSession("routerData", routerData);123 },124 SET_ACCOUNTTYPE: (state, accountType) => {125 state.accountType = accountType;126 Storage.saveSession("accountType", accountType);127 },128 SET_PROJECTTYPE: (state, projectType) => {129 state.projectType = projectType;130 Storage.saveSession("projectType", projectType);131 },132 SET_TAG_HOLD_NUM: (state, tagHoldNum) => {133 state.tagHoldNum = tagHoldNum;134 Storage.saveSession("tagHoldNum", tagHoldNum);135 },136 SET_MAP_SET_DATA: (state, mapSetData) => {137 state.mapSetData = mapSetData;138 Storage.saveSession("mapSetData", mapSetData);139 },140 },141 actions: {142 setTagViewArr({ commit }, tagViewArr) {143 commit("SET_TAG_VIEW_ARR", tagViewArr);144 },145 clearTagView({ commit }) {146 commit("CLEAR_TAG_VIEW");147 },148 setLocalTag({ commit }, localTag) {149 commit("SET_LOCAL_TAG", localTag);150 },151 addTagViewItem({ commit }, compomentItem) {152 commit("ADD_TAG_VIEW_ITEM", compomentItem);...
saveController.test.js
Source:saveController.test.js
1describe('SaveController', function () {2 beforeEach(function() {3 this.eventEmitter = new Mirador.EventEmitter();4 this.config = {5 id: 'mock_viewer_id',6 saveSession: false,7 eventEmitter: this.eventEmitter8 }; 9 });10 11 describe('Constructor', function () {12 xit ('should fail gracefully when storage is invalid or unavailable', function () {13 // When saveSession is true and the storage module fails to initiate,14 // display proper error message to user and possibly revert to 'no save' mode.15 });16 });17 18 describe('Sanity check when saveSession == false', function () {19 beforeEach(function () {20 this.config.saveSession = false;21 this.saveController = new Mirador.SaveController(this.config);22 });23 it('should not have this.storageModule', function () {24 expect(this.saveController.storageModule).toBe(undefined);25 });26 it ('should respond to published events', function () {27 // Just making sure bindEvents() is being called.28 29 // windowUpdated30 this.eventEmitter.publish('windowUpdated', {});31 expect(this.saveController.get('windowObjects', 'currentConfig')).toEqual([{}]);32 });33 });34 describe('Sanity check when saveSession == true', function () {35 36 beforeEach(function () {37 this.config.saveSession = true;38 this.saveController = new Mirador.SaveController(this.config);39 });40 it('should have _this.storageModule', function () {41 expect(this.saveController.storageModule).toBeTruthy();42 });43 it ('should respond to published events', function () {44 // Just making sure bindEvents() is being called.45 46 // windowUpdated47 this.eventEmitter.publish('windowUpdated', {});48 expect(this.saveController.get('windowObjects', 'currentConfig')).toEqual([{}]);49 });50 });51 52 describe('Working with localStorage', function () {53 xit('should deal with localStorage', function () {54 });55 });56 describe('Working with jsonStorageEndpoint', function () {57 beforeEach(function () {58 window.Mirador.MockJsonStorege = function () {59 this.readSync = function (blobId) {60 return {61 hash_1: { id: 'stored_config_1',62 windowObjects: []63 }64 }[blobId];65 };66 };67 this.config.jsonStorageEndpoint = {68 'name': 'Mock JSON Storage Endpoint',69 'module': 'MockJsonStorege'70 };71 this.config.saveSession = true;72 history.replaceState({}, 'History replaced', '/?key=hash_1');73 74 this.saveController = new Mirador.SaveController(this.config);75 });76 77 it('should read config from storage', function () {78 expect(this.saveController.currentConfig.id).toBe('stored_config_1');79 });80 });81 82 describe('getWindowObjectById', function () {83 beforeEach(function () {84 this.config.saveSession = false;85 this.saveController = new Mirador.SaveController(this.config);86 });87 // TODO porbably should test for different values of saveSession and 88 // storage engines.89 it('should retrieve the saved window object', function () {90 this.config.saveSeesion = false;91 this.config.windowObjects = [ 92 { id: 'mock_window_1' },93 { id: 'mock_window_2' } 94 ];95 var saveController = new Mirador.SaveController(this.config);96 expect(saveController.getWindowObjectById('mock_window_1').id).toBe('mock_window_1');97 expect(saveController.getWindowObjectById('mock_window_2').id).toBe('mock_window_2');98 });99 });100 101 describe('Get and set properties', function () {102 it('should retrieve saved values', function () {103 var saveController = new Mirador.SaveController(this.config);104 105 saveController.set('key_1', 'val_1');106 saveController.set('key_2', 'val_2', { parent: 'currentConfig'});107 expect(saveController.get('key_1')).toBe('val_1');108 expect(saveController.get('key_2', 'currentConfig')).toBe('val_2');109 expect(saveController.getStateProperty('key_2')).toBe('val_2');110 });111 });112 113 describe('Event handling', function () {114 xit('should handle windowUpdated', function () {115 });116 xit('should handle imageBoundsUpdated', function () {117 });118 119 it('should handle ANNOTATIONS_LIST_UPDATED', function () {120 var saveController = new Mirador.SaveController(this.config);121 var windowId = 'mock_window_1';122 var annotationsList = [123 { '@id': 'mock_annotation_1' },124 { '@id': 'mock_annotation_2' }125 ];126 this.eventEmitter.publish('ANNOTATIONS_LIST_UPDATED', { windowId: windowId, 127 annotationsList: annotationsList });128 expect(saveController.getWindowAnnotationsList(windowId)[0]['@id']).toBe('mock_annotation_1');129 expect(saveController.getWindowAnnotationsList(windowId)[1]['@id']).toBe('mock_annotation_2');130 });131 132 xit('should handle WINDOW_ELEMENT_UPDATED', function nnn() {133 });134 135 xit('should handle windowSlotAddressUpdated', function () {136 });137 138 xit('should handle manifestQueued', function () {139 });140 141 xit('should handle slotsUpdated', function () {142 });143 xit('should handle layoutChanged', function () {144 });145 146 xit('should handle windowSlotAdded', function () {147 });148 149 xit('should handle windowsRemoved', function () {150 });151 152 xit('should handle ...etc', function () {153 // What the heck is this.154 });155 });156 ...
data-logging-service.spec.js
Source:data-logging-service.spec.js
...14 test('it validates that a session ID is provided', () => {15 const expectedMessage = 'session_id: A string session ID is required';16 // Falsy ID17 testInput.session_id = null;18 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);19 testInput.session_id = '';20 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);21 // Wrong type22 testInput.session_id = 42;23 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);24 // Missing ID25 delete testInput.session_id;26 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);27 });28 test('it validates that a combined array of selected terms is provided', () => {29 const expectedMessage = 'selected_terms: An array of HPO terms is required';30 testInput.selected_terms = null;31 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);32 testInput.selected_terms = {};33 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);34 testInput.selected_terms = [{ nope: 'not a term' }];35 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);36 delete testInput.selected_terms;37 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);38 });39 test('it validates that constrained mode terms are provided', () => {40 const expectedMessage = 'constrained_terms: An array of HPO terms is required';41 testInput.constrained_terms = null;42 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);43 testInput.constrained_terms = {};44 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);45 testInput.constrained_terms = [{ nope: 'not a term' }];46 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);47 delete testInput.constrained_terms;48 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);49 });50 test('it validates that unconstrained mode terms are provided', () => {51 const expectedMessage = 'unconstrained_terms: An array of HPO terms is required';52 // empty array should be accepted53 testInput.unconstrained_terms = [];54 expect(() => { service.saveSession(testInput); }).not.toThrow();55 testInput.unconstrained_terms = null;56 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);57 testInput.unconstrained_terms = {};58 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);59 testInput.unconstrained_terms = [{ nope: 'not a term' }];60 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);61 delete testInput.unconstrained_terms;62 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);63 });64 test('it validates that body systems are provided', () => {65 const expectedMessage = 'selected_systems: An array of HPO IDs is required';66 testInput.selected_systems = null;67 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);68 testInput.selected_systems = {};69 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);70 testInput.selected_systems = ['not an ID'];71 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);72 delete testInput.selected_systems;73 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);74 });75 test('it validates that the feedback flag is provided', () => {76 const expectedMessage = 'found_all: Should be true or false';77 testInput.found_all = null;78 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);79 testInput.found_all = {};80 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);81 testInput.found_all = 42;82 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);83 delete testInput.found_all;84 expect(() => { service.saveSession(testInput); }).toThrow(expectedMessage);85 });86 test('it posts to the persistence endpoint', () => {87 const expectedBody = { search_results: testInput };88 return service.saveSession(testInput)89 .then(() => {90 expect(axios.post).toHaveBeenCalledWith(MOCK_ENDPOINT, expectedBody);91 });92 });...
cart.js
Source:cart.js
...35 };36 }37 return item;38 });39 saveSession(CART_ITEMS, localCartItems);40 return { cartItems: tempCartItems, status: 200 };41}42export async function removeItemFromCartByIdApi(id, _) {43 const ALL_CART_ITEMS = loadSession(CART_ITEMS);44 const itemList = objectToArray(ALL_CART_ITEMS, 'id');45 deleteCart(itemList[id].entry_id);46 const localCartItems = ALL_CART_ITEMS.filter(prevItem => {47 return id !== prevItem.id;48 });49 const tempCartItems = ALL_CART_ITEMS.filter(prevItem => {50 return id !== prevItem.id;51 });52 saveSession(CART_ITEMS, localCartItems);53 // setCart(localCartItems);54 return { cartItems: tempCartItems, status: 200 };55}56export async function addToRemoveListApi(id, toRemove, cartItems) {57 const ALL_CART_ITEMS = loadSession(CART_ITEMS);58 const localCartItems = ALL_CART_ITEMS.filter(prevItem => {59 if (id === prevItem.id) {60 if (toRemove) {61 prevItem.isRemove = true;62 } else {63 prevItem.isRemove = false;64 }65 }66 return prevItem;67 });68 const tempCartItems = cartItems.filter(prevItem => {69 if (id === prevItem.id) {70 if (toRemove) {71 prevItem.isRemove = true;72 } else {73 prevItem.isRemove = false;74 }75 }76 return prevItem;77 });78 saveSession(CART_ITEMS, localCartItems);79 return { cartItems: tempCartItems };80}81export async function addToPaypalTransactionApi(paypalTxDetails) {82 saveSession(CART_ITEMS, []);83 return paypalTxDetails;84}85export async function callUpdateMyVouchersApi(paypalTxDetails) {86 const items = await updateMyVouchersApi(paypalTxDetails);87 const emptyCart = (CART_ITEMS, []);88 // setCart(emptyCart);89 return items;90}91export async function addAllToRemoveListApi(toRemoveAll, cartItems) {92 const ALL_CART_ITEMS = loadSession(CART_ITEMS);93 const localCartItems = ALL_CART_ITEMS.filter(prevItem => {94 if (toRemoveAll) {95 prevItem.isRemove = true;96 } else {97 prevItem.isRemove = false;98 }99 return prevItem;100 });101 const tempCartItems = cartItems.filter(prevItem => {102 if (toRemoveAll) {103 prevItem.isRemove = true;104 } else {105 prevItem.isRemove = false;106 }107 return prevItem;108 });109 saveSession(CART_ITEMS, localCartItems);110 return { cartItems: tempCartItems };111}112export async function removeAllFromCartApi(items = []) {113 const targetIds = loadSession('ids');114 const cartItems = items.filter(item => !targetIds.includes(item.id));115 const lsCartItems = loadSession(CART_ITEMS) || [];116 purgeSession('ids');117 saveSession(118 CART_ITEMS,119 lsCartItems.filter(({ id }) => !targetIds.includes(id))120 );121 await lsCartItems.map(async ({ entry_id, id }) => {122 targetIds.includes(id) && (await deleteCart(entry_id));123 });124 return { cartItems };...
helpers.js
Source:helpers.js
1export function saveRegistrationSession(dispatchFn, data) {2 saveSession(dispatchFn, "registration", data);3}4export function saveHelpdeskSession(dispatchFn, data) {5 saveSession(dispatchFn, "helpdesk", data);6}7export function saveFraudSession(dispatchFn, data) {8 saveSession(dispatchFn, "fraud", data);9}10export function saveTrustStoreSession(dispatchFn, data) {11 saveSession(dispatchFn, "trust_store", data);12}13export function saveGG3Session(dispatchFn, data) {14 saveSession(dispatchFn, "gg3", data);15}16export function saveResetPasswordSession(dispatchFn, data) {17 saveSession(dispatchFn, "reset_password", data);18}19export function saveSpacegovSession(dispatchFn, data) {20 saveSession(dispatchFn, "spacegov", data);21}22export function saveAsteroidgovSession(dispatchFn, data) {23 saveSession(dispatchFn, "asteroidgov", data);24}25export function saveCredentialSession(dispatchFn, data) {26 saveSession(dispatchFn, "credential", data);27}28export function saveOrgSession(dispatchFn, data) {29 saveSession(dispatchFn, "org", data);30}31export function clearCredentialSession(dispatchFn) {32 clearSession(dispatchFn, "credential");33}34export function clearRegistrationSession(dispatchFn) {35 clearSession(dispatchFn, "registration");36}37export function clearHelpdeskSession(dispatchFn) {38 clearSession(dispatchFn, "helpdesk");39}40export function clearFraudSession(dispatchFn) {41 clearSession(dispatchFn, "fraud");42}43export function clearTrustStoreSession(dispatchFn) {44 clearSession(dispatchFn, "trust_store");45}46export function clearGG3Session(dispatchFn) {47 clearSession(dispatchFn, "gg3");48}49export function clearOrg(dispatchFn) {50 clearSession(dispatchFn, "org");51}52export function clearResetPasswordSession(dispatchFn) {53 clearSession(dispatchFn, "reset_password");54}55export function clearSpacegovSession(dispatchFn) {56 clearSession(dispatchFn, "spacegov");57}58export function clearAsteroidgovSession(dispatchFn) {59 clearSession(dispatchFn, "asteroidgov");60}61export function clearAllSessions(dispatchFn) {62 clearRegistrationSession(dispatchFn);63 clearHelpdeskSession(dispatchFn);64 clearGG3Session(dispatchFn);65 clearSpacegovSession(dispatchFn);66 clearAsteroidgovSession(dispatchFn);67 clearCredentialSession(dispatchFn);68 clearResetPasswordSession(dispatchFn);69 clearTrustStoreSession(dispatchFn);70 clearFraudSession(dispatchFn);71 clearOrg(dispatchFn);72}73export function importSession(dispatchFn, data) {74 dispatchFn( {type: 'IMPORT_SESSION', data})75}76function saveSession(dispatchFn, name, data) {77 dispatchFn( {type: 'SAVE_SESSION', name, data})78}79function clearSession(dispatchFn, name) {80 dispatchFn( {type: 'CLEAR_SESSION', name})...
session-helper.test.js
Source:session-helper.test.js
...11 })12 context('session save success', () => {13 beforeEach(async () => {14 this.reqMock.session.save.yields()15 await this.saveSession(this.reqMock.session)16 })17 it('should call saveSession', () => {18 expect(this.saveSession).to.have.been.calledOnce19 })20 it('should call session save method', () => {21 expect(this.reqMock.session.save).to.have.been.calledOnce22 })23 })24 context('session save error', () => {25 beforeEach(async () => {26 this.returnedError = 'huston we have a problem!'27 this.reqMock.session.save.yields(this.returnedError)28 try {29 await this.saveSession(this.reqMock.session)30 } catch (error) {31 this.error = error32 }33 })34 it('should call saveSession', () => {35 expect(this.saveSession).to.have.been.calledOnce36 })37 it('should call session save method', () => {38 expect(this.reqMock.session.save).to.have.been.calledOnce39 })40 it('should handle error as expected', () => {41 expect(this.error).to.equal(this.returnedError)42 })43 })...
AppComponent.js
Source:AppComponent.js
1import AppComponent from '../AppComponent'2import { defaultSettings, defaultWorkspaces } from 'constants/defaultValues'3const baseProps = {4 allSettings: defaultSettings,5 allWorkspaces: { 0: defaultWorkspaces },6 actions: {7 appSetup: jest.fn(),8 saveSession: jest.fn(),9 },10}11let wrapper12describe('AppComponent', () => {13 beforeEach(() => {14 jest.clearAllMocks()15 wrapper = shallow(<AppComponent {...baseProps} />)16 })17 afterAll(() => {18 wrapper.unmount()19 })20 it('renders without crashing', () => {21 expect(wrapper.exists()).toBeTruthy()22 })23 it('componentDidMount calls appSetup', () => {24 const { appSetup } = baseProps.actions25 expect(appSetup).toHaveBeenCalled()26 })27 it('componentDidUpdate calls saveSession w/ autoSave', () => {28 const { saveSession } = baseProps.actions29 const nextProps = { ...baseProps, test: 'test' }30 wrapper.instance().componentDidUpdate(nextProps, null)31 expect(saveSession.mock.calls.length).toBe(1)32 })33 it('componentDidUpdate ignores saveSession w/ !autoSave', () => {34 const { saveSession } = baseProps.actions35 const nextProps = {36 ...baseProps,37 allSettings: {38 ...baseProps.allSettings,39 autoSave: false,40 },41 }42 wrapper.instance().componentDidUpdate(nextProps, null)43 expect(saveSession.mock.calls.length).toBe(0)44 })...
Using AI Code Generation
1Cypress.Commands.add('saveSession', () => {2 cy.window().then((win) => {3 win.sessionStorage.clear()4 for (let i = 0; i < win.sessionStorage.length; i++) {5 let key = win.sessionStorage.key(i)6 cy.log(key + " : " + win.sessionStorage.getItem(key))7 cy.setCookie(key, win.sessionStorage.getItem(key))8 }9 })10})11Cypress.Commands.add('clearSession', () => {12 cy.window().then((win) => {13 win.sessionStorage.clear()14 for (let i = 0; i < win.sessionStorage.length; i++) {15 let key = win.sessionStorage.key(i)16 cy.clearCookie(key)17 }18 })19})20Cypress.Commands.add('saveSession', () => {21 cy.window().then((win) => {22 win.sessionStorage.clear()23 for (let i = 0; i < win.sessionStorage.length; i++) {24 let key = win.sessionStorage.key(i)25 cy.log(key + " : " + win.sessionStorage.getItem(key))26 cy.setCookie(key, win.sessionStorage.getItem(key))27 }28 })29})30Cypress.Commands.add('clearSession', () => {31 cy.window().then((win) => {32 win.sessionStorage.clear()33 for (let i = 0; i < win.sessionStorage.length; i++) {34 let key = win.sessionStorage.key(i)35 cy.clearCookie(key)36 }37 })38})39Cypress.Commands.add('saveLocalStorage', () => {40 Object.keys(localStorage).forEach(key => {41 cy.log(key + " : " + localStorage.getItem(key))42 cy.setCookie(key, localStorage.getItem(key))43 })44})45Cypress.Commands.add('clearLocalStorage', () => {46 Object.keys(localStorage).forEach(key => {47 cy.clearCookie(key)48 })49})50Cypress.Commands.add('clearCookies', () => {51 cy.getCookies().then(cookies => {52 for (let cookie of cookies) {
Using AI Code Generation
1Cypress.Commands.add("saveSession", () => {2 Cypress.log({3 });4 cy.window()5 .its("sessionStorage")6 .invoke("getItem", "reduxState")7 .then((sessionStorageValue) => {8 cy.setCookie("sessionStorage", sessionStorageValue);9 });10});11Cypress.Commands.add("restoreSession", () => {12 Cypress.log({13 });14 cy.getCookies().then((cookies) => {15 const value = cookies.find((cookie) => cookie.name === "sessionStorage")16 .value;17 cy.window().then((win) => {18 win.sessionStorage.setItem("reduxState", value);19 });20 });21});
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('
Using AI Code Generation
1Cypress.Commands.add('saveSession', () => {2 Cypress.log({3 })4 cy.window().then((win) => {5 win.sessionStorage.clear()6 })7 cy.document().then((doc) => {8 doc.cookie.split(';').forEach(c => {9 cy.setCookie(c.split('=')[0], c.split('=')[1])10 })11 })12})13Cypress.Commands.add('restoreSession', () => {14 Cypress.log({15 })16 cy.window().then((win) => {17 Object.keys(win.sessionStorage).forEach(key => {18 cy.sessionStorage(key, win.sessionStorage[key])19 })20 })21 cy.getCookies().then(cookies => {22 cookies.forEach(c => {23 cookie += `${c.name}=${c.value};`24 })25 cy.setCookie(null, cookie)26 })27})28Cypress.Commands.add('saveLocalStorage', () => {29 Cypress.log({30 })31 Object.keys(localStorage).forEach(key => {32 cy.localStorage(key, localStorage[key])33 })34})35Cypress.Commands.add('restoreLocalStorage', () => {36 Cypress.log({37 })38 Object.keys(localStorage).forEach(key => {39 cy.localStorage(key, localStorage[key])40 })41})42Cypress.Commands.add('saveStorage', () => {43 cy.saveLocalStorage()44 cy.saveSession()45})46Cypress.Commands.add('restoreStorage', () => {47 cy.restoreLocalStorage()48 cy.restoreSession()49})50Cypress.Commands.add('clearStorage', () => {51 Cypress.log({52 })53 cy.clearLocalStorage()54 cy.clearCookies()55})56Cypress.Commands.add('clearSessionStorage
Using AI Code Generation
1Cypress.Commands.add("saveSession", () => {2 Cypress.log({3 });4 cy.window().then((win) => {5 win.sessionStorage.clear();6 });7 cy.session(8 (session) => {9 Cypress.log({10 });11 return session;12 },13 {14 validate: (session) => {15 Cypress.log({16 });17 return session && session.authToken;18 },19 }20 );21});22Cypress.Commands.add("saveSession", () => {23 Cypress.log({24 });25 cy.window().then((win) => {26 win.sessionStorage.clear();27 });28 cy.session(29 (session) => {30 Cypress.log({31 });32 return session;33 },34 {35 validate: (session) => {36 Cypress.log({37 });38 return session && session.authToken;39 },40 }41 );42});43Cypress.Commands.add("saveSession", () => {44 Cypress.log({45 });46 cy.window().then((win) => {47 win.sessionStorage.clear();48 });49 cy.session(50 (session) => {51 Cypress.log({52 });53 return session;54 },55 {56 validate: (session) => {57 Cypress.log({58 });59 return session && session.authToken;60 },61 }62 );
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!