Best JavaScript code snippet using testcafe
igrp_blockly_elements.js
Source:igrp_blockly_elements.js  
...27				28		 decompose: function (workspace) {29		        var containerBlock = workspace.newBlock('where_t');30		        containerBlock.initSvg();31		        var connection = containerBlock.getInput('SCRIPT').connection;	  32		        for (var i = 1; i <= this.itemCount_; i++) { 33		            var itemBlock = workspace.newBlock('where');34		            itemBlock.initSvg();35		            connection.connect(itemBlock.previousConnection);36		            connection = itemBlock.nextConnection; 37		        }38		        return containerBlock;39		    },40		    41		 compose: function (containerBlock) {42		        var itemBlock = containerBlock.getInputTargetBlock('SCRIPT');43		        var connections = [];44		        while (itemBlock) {45		            connections.push(itemBlock.valueConnection_);46		            itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();47		        }48		        for (var i = 1; i <= this.itemCount_; i++) {49		            var connection = this.getInput('ADD' + i).connection.targetConnection;50		            if (connection && connections.indexOf(connection) == -1) {51		                //connection.disconnect();52		            } 53		        }54		        this.itemCount_ = connections.length;55		        this.updateShape_();56		        for (var i = 1; i <= this.itemCount_; i++) {57		            Blockly.Mutator.reconnect(connections[i], this, 'ADD' + i);58		        }59		    },60		    61		 updateShape_: function (arr) {62			 	var _block = this;63			 	var mutation_num = this.itemCount_;64			 	if(_block.getInput("get_pa")!= null)65		 		{66				 	if(mutation_num != 0){67				 		_block.getInput("get_pa").setVisible(false);	68				 	}69				 	else{70				 		_block.getInput("get_pa").setVisible(true);		71				 	}72		 		}73			 	if(_block.getInput("empty_table")!= null)74		 		{75				 	if(mutation_num != 0){76				 		_block.getInput("empty_table").setVisible(true);	77				 	}78				 	else{79				 		_block.getInput("empty_table").setVisible(false);	80				 	}81		 		}82			 	var appendMutationFields = function(v,id){83			 		if(v == 'andWhere' || v == 'orWhere' || v == 'where' || v == 'having'  )	84            		{85			 			_block.getInput('ADD'+ id).setVisible(true);86			 			_block.getInput('ADD'+ id +'SIGNAL').setVisible(true);87			 			_block.getInput('ADD'+ id +'STATE2').setVisible(true);88			 			_block.getInput('ADD'+ id +'STATE3').setVisible(false);	89            		}90			 		if(v == 'andWhereBetween' || v == 'orWhereBetween' )	91            		{92			 			_block.getInput('ADD'+ id).setVisible(true);93			 			_block.getInput('ADD'+ id +'SIGNAL').setVisible(false);94			 			_block.getInput('ADD'+ id +'STATE2').setVisible(true);95			 			_block.getInput('ADD'+ id +'STATE3').setVisible(true);96            		}97			 		if(v == 'andWhereIsNull' || v == 'andWhereIsNotNull' || v == 'orWhereIsNull' || v == 'orWhereIsNotNull' )	98            		{99			 			_block.getInput('ADD'+ id).setVisible(true);100			 			_block.getInput('ADD'+ id +'SIGNAL').setVisible(false);101			 			_block.getInput('ADD'+ id +'STATE2').setVisible(false);102			 			_block.getInput('ADD'+ id +'STATE3').setVisible(false);103            		}104			 	}105			 	var getDDField = function(idx){106			 		return new Blockly.FieldDropdown(FILTER, function(input_type){107	            		appendMutationFields(input_type,idx)108	            	})109			 	}110		        for (var i = 1; i <= this.itemCount_; i++) {111		            if (!this.getInput('ADD' + i)) {112		             	var fdpFilter = new getDDField(i);113		             	this.appendValueInput('ADD' + i).appendField(fdpFilter,'ADD'+i+'FILTER').setVisible(true);114	    	        	this.appendDummyInput('ADD' + i+'SIGNAL').appendField(new Blockly.FieldDropdown(WHERE),'ADD'+i+'WHERE').setVisible(true);115	    	        	this.appendValueInput('ADD'+ i +'STATE2').setVisible(true);116	    	        	this.appendValueInput('ADD'+ i +'STATE3').setVisible(false);117		            }118		        }119		        if(arr && arr[0])120			        arr.forEach(function(v,x){121			        	appendMutationFields(v,x+1);122			        })123		        while (this.getInput('ADD' + i)) {124		            this.removeInput('ADD' + i);125		            this.removeInput('ADD'+i+'STATE1');126		            this.removeInput('ADD'+i+'SIGNAL');127		            this.removeInput('ADD'+i+'STATE2');128		            this.removeInput('ADD'+i+'STATE3');129		            i++;130		        }       131		    }	    132	}133	134	//////////////////////////////////////////////START IGRP_BLOCKLY_ELEMENTS ////////////////////////////////////////////////////////135	136	window.IGRP_BLOCKLY_ELEMENTS = {137			138		listar : $.extend({139			140			init : function(block){141				block.itemCount_ = 0;142				block.updateShape_();143				block.updateShape__ = function(){};144//				this.onTableSet = function(item){		145//					var XML = $.parseXML(VARS.getGen().getXML());	146//					var menus = function(){147//						var arr = [];148//						$('rows content '+item, XML).find('fields > *').each(function(i, field){	149//							var type =  GetJavaType[$(field).attr('type')] || 'String';150//							arr.push( [ field.tagName, type+'::'+ field.tagName ] )151//						})152//						return arr153//					}();154//				}	155			}156		}, ListMutationSettings),157		158		159	 combo_dao :$.extend({160161		init : function(block){162			 block.itemCount_ = 0;163			 block.updateShape_();164			 block.updateShape__ = function(){};165		}	166	  }, ListMutationSettings),167	  168	  169	 index_editar :$.extend({170		  171			init : function(block){172				block.itemCount_ = 0;173				block.updateShape_();174				block.updateShape__ = function(){};175			}	176		  }, ListMutationSettings),177  178		  179	 separator :$.extend({180		 181		init : function(block){182			block.itemCount_ = 0;183			block.updateShape_();184			block.updateShape__ = function(){};185		}	186	  }, ListMutationSettings),187	  188	  189	 formlist :$.extend({190			191		init : function(block){192			block.itemCount_ = 0;193			block.updateShape_();194			block.updateShape__ = function(){};195		}	196	  }, ListMutationSettings),197		198	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////199	  200	inserir_dao : {201		202		init : function(block){203			block.itemCount_ = 0;204			block.updateShape_();205			var checkbox = new Blockly.FieldCheckbox("FALSE", function(pxchecked) {206				this.sourceBlock_.updateShape_(pxchecked);207			});	208		},209		mutationToDom: function() {210			  var container = document.createElement('mutation');211			  container.setAttribute('count', this.itemCount_);212			  var pxchecked = (this.getFieldValue('EDIT') == 'TRUE');213			  container.setAttribute('pxchecked', pxchecked);214			  return container;215		},	216		domToMutation: function(xmlElement) {217			var pxchecked = (xmlElement.getAttribute('pxchecked') == 'true');218			this.itemCount_ = parseInt(xmlElement.getAttribute('count'), 10);219			this.updateShape_(pxchecked);220		},	221		222		decompose: function (workspace) {223	        var containerBlock = workspace.newBlock('insert_t');224	        containerBlock.initSvg();225	        var connection = containerBlock.getInput('SCRIPT').connection;	 226	        for (var i = 0; i < this.itemCount_; i++) { 227	            var itemBlock = workspace.newBlock('separatori');228	            itemBlock.initSvg();229	            connection.connect(itemBlock.previousConnection);230	            connection = itemBlock.nextConnection;231	        }232	        return containerBlock; 233	  },234	  compose: function (containerBlock) {235	        var itemBlock = containerBlock.getInputTargetBlock('SCRIPT');236	        var connections = [];237	        while (itemBlock) {238	            connections.push(itemBlock.valueConnection_);239	            itemBlock = itemBlock.nextConnection && itemBlock.nextConnection.targetBlock();240	        }241	      for (var i = 1; i < this.itemCount_; i++) {242	            var connection = this.getInput('SEPARATOR'+i).connection.targetConnection;243	            if (connection && connections.indexOf(connection) == -1) {244	                //connection.disconnect();245	            } 246	        }247	        this.itemCount_ = connections.length;248	        Contador = this.itemCount_;249	        this.updateShape_();250	        for (var i = 1; i <= this.itemCount_; i++) {251	            Blockly.Mutator.reconnect(connections[i], this, 'SEPARATOR'+i); 252	        }253	    },254255	    updateShape_: function (pxchecked) {256		    var block = this;257		    pxchecked = typeof pxchecked === 'undefined' ? this.getFieldValue('EDIT') == 'TRUE' : pxchecked;258	        for (var i = 1; i <= this.itemCount_; i++) {259	            if (!this.getInput('SEPARATOR'+i)) { 260    	        	this.appendDummyInput('SEPARATORIL'+i).appendField("add insert");261    	        	this.appendStatementInput('SEPARATOR'+i);262	            }263	        }264	        while (this.getInput('SEPARATOR'+i)) {265	            this.removeInput('SEPARATOR'+i);266	            this.removeInput('SEPARATORIL'+i); 267	            i++; 268	        } 269	        this.removeInput('param_id');270	        if (pxchecked) {271			      block.appendValueInput("param_id").appendField("find");272			      block.moveInputBefore("param_id", "value2");273			} else {274			  this.removeInput('param_id');275		      if (this.childBlocks_.length > 0) {276		        for (var i = 0; i < block.childBlocks_.length; i++) {277		          if (block.childBlocks_[i].type == 'px') {  278			           block.childBlocks_[i].unplug();279			           break;280		          }281		        }282		      }283			}284	    }285	},286		287		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////288		  289		290	checkbox_table : {291		292		init : function(block){293			block.itemCount_ = 0;294			var checkbox = new Blockly.FieldCheckbox("FALSE", function(pxchecked) {295				this.sourceBlock_.updateShape_(pxchecked);296			});	297		block.appendDummyInput().appendField(checkbox, 'UNSEL');298		block.appendStatementInput("value_selected");299		block.mutationToDom =  function() {300		    var container = document.createElement('mutation');301		    var pxchecked = (this.getFieldValue('UNSEL') == 'TRUE');302		    container.setAttribute('pxchecked', pxchecked);303		    return container; 304		},305306		block.domToMutation = function(xmlElement) {307			var pxchecked = (xmlElement.getAttribute('pxchecked') == 'true');308			this.updateShape_(pxchecked);309		},310		311		block.updateShape_  = function(pxchecked) {	312		    var check = pxchecked;313	        if (pxchecked) {314	        		block.appendDummyInput("tete").appendField("unselecteds");315			      block.appendStatementInput("value_unselected");316			} else {317			  this.removeInput('tete');318			  this.removeInput('value_unselected');319		      320			}321	    }322		323		}324	},325		326///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////327		328		//Handle with CORE BLOCK329		330		core_fun_set : {331			332			init : function(block){333			var options = IGRP_BLOCKLY_DROPS.core;334			var dropdown = new Blockly.FieldDropdown(options, function(option) {	335				this.sourceBlock_.updateShape_(option);    336		    });	337		    block.getInput("CORE").appendField(dropdown, 'CORE_FUNCTION')338			     .appendField(new Blockly.FieldImage(path+"/core/blockly/blockly/media/igrpweb_logo.png",40,20,"*"));339		    block.setInputsInline(true);340		    block.appendValueInput("value1").setVisible(false);341		    block.appendValueInput("value2").setVisible(false);342		    block.appendValueInput("value3").setVisible(false);343		    block.appendValueInput("value4").setVisible(false);344		    block.appendValueInput("value5").setVisible(false);345		    346			block.mutationToDom =  function() {347			    var container = document.createElement('mutation');348			    var itemInput = this.getFieldValue('CORE_FUNCTION');349			    container.setAttribute('hover_type', itemInput);350			    return container; 351			},352353			block.domToMutation = function(xmlElement) {354			    var itemInput = xmlElement.getAttribute('hover_type');355			    this.updateShape_(itemInput);  356			},357			358			block.updateShape_  = function(input_type) {		 359			 	var type    = input_type;360361			    if (type == 'enviar_email') {362					block.getInput("value1").setVisible(true);363					block.getInput("value2").setVisible(true);364					block.getInput("value3").setVisible(true);365					block.getInput("value4").setVisible(true);366					block.getInput("value5").setVisible(true);367			    }368			    else {369					block.getInput("value1").setVisible(false);370					block.getInput("value2").setVisible(false);371					block.getInput("value3").setVisible(false);372					block.getInput("value4").setVisible(false);373					block.getInput("value5").setVisible(false);374			    }375			  }376			}377		},378		379	core_fun_get : {380			381			init : function(block){382			var options = IGRP_BLOCKLY_DROPS.core;383			var dropdown = new Blockly.FieldDropdown(options, function(option) {	384				this.sourceBlock_.updateShape_(option);    385		    });	386		    block.getInput("CORE").appendField(dropdown, 'CORE_FUNCTION')387			     .appendField(new Blockly.FieldImage(path+"/core/blockly/blockly/media/igrpweb_logo.png",40,20,"*"));388		    block.setInputsInline(true);389		    block.appendValueInput("value1").setVisible(false);390		    block.appendValueInput("value2").setVisible(false);391		    block.appendValueInput("value3").setVisible(false);392		    block.appendValueInput("value4").setVisible(false);393		    block.appendValueInput("value5").setVisible(false);394		    395			block.mutationToDom =  function() {396			    var container = document.createElement('mutation');397			    var itemInput = this.getFieldValue('CORE_FUNCTION');398			    container.setAttribute('hover_type', itemInput);399			    return container; 400			},401402			block.domToMutation = function(xmlElement) {403			    var itemInput = xmlElement.getAttribute('hover_type');404			    this.updateShape_(itemInput);  405			},406			407			block.updateShape_  = function(input_type) {		 408			 	var type    = input_type;409410			    if (type == 'enviar_email') {411					block.getInput("value1").setVisible(true);412					block.getInput("value2").setVisible(true);413					block.getInput("value3").setVisible(true);414					block.getInput("value4").setVisible(true);415					block.getInput("value5").setVisible(true);416			    }417			    else if (type == 'apanhar_parametro_texto') {418					block.getInput("value1").setVisible(true);419					block.getInput("value2").setVisible(false);420					block.getInput("value3").setVisible(false);421					block.getInput("value4").setVisible(false);422					block.getInput("value5").setVisible(false);423			    }424			    else if (type == 'get_domain') {425					block.getInput("value1").setVisible(true);426					block.getInput("value2").setVisible(true);427					block.getInput("value3").setVisible(false);428					block.getInput("value4").setVisible(false);429					block.getInput("value5").setVisible(false);430			    }431			    else {432					block.getInput("value1").setVisible(false);433					block.getInput("value2").setVisible(false);434					block.getInput("value3").setVisible(false);435					block.getInput("value4").setVisible(false);436					block.getInput("value5").setVisible(false);437			    }438			  }439			}440		},441		442	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////443		444	grafico :$.extend({445			446			init : function(block){447				448				block.itemCount_ = 0;449				block.updateShape_();450				451				 var checkbox = new Blockly.FieldCheckbox("TRUE", function(pxchecked) {452				      			this.sourceBlock_.updateShape__(pxchecked);			453				 });454				 455				//block.appendDummyInput().appendField("3D").appendField(checkbox, '3D');	456			 457				 block.updateShape__ = function(pxchecked) {458				    if (pxchecked) {459				      block.appendValueInput("eixoZ").appendField("Eixo Z");460				    } else {461				      if (this.childBlocks_.length > 0) {462					        for (var i = 0; i < block.childBlocks_.length; i++) {463						          if (block.childBlocks_[i].type == 'px') { 464							           block.childBlocks_[i].unplug();465							           break;466						          }   467					        } 468				      }469				      this.removeInput('eixoZ'); 470				    }471				 } 472			}473			474		}, ListMutationSettings),475	476	}477	478	/////////////////////////////////////////////  END IGRP_BLOCKLY_ELEMENTS  /////////////////////////////////////////////////479	480//Handle SET Dao Blocks481	482	$(document).on('set-dao-block-init', function(e, block, dao){	483		var options = IGRP_BLOCKLY_DROPS.daos[dao];484		var dropdown = new Blockly.FieldDropdown(options, function(option) {	485			this.sourceBlock_.updateShape_(option);    486	    });	487		block.setColour(160);488	    block.getInput("value1").appendField(dropdown, 'DAO_FIELD')489		     .appendField(new Blockly.FieldImage(path+"/core/blockly/blockly/media/dao.svg",15,15,"*"));490	    491		block.mutationToDom =  function() {492		    var container = document.createElement('mutation');493		    var itemInput = this.getFieldValue('DAO_FIELD');494		    container.setAttribute('hover_type', itemInput);495		    return container; 496		},497498		block.domToMutation = function(xmlElement) {499		    var itemInput = xmlElement.getAttribute('hover_type');500		    this.updateShape_(itemInput);  501		},502		503		block.updateShape_  = function(input_type) {		 504		 	var strSplit    = input_type.split('::'),505				type        = strSplit[0],506				val 	    = strSplit[1],507		        inputExists = this.getInput('dao_rela'); 508		    if (type.includes("_FK#")) {509		      if (!inputExists) {510		        this.setInputsInline(true);511		      }512		    }else513		    try{514		    	this.setInputsInline(false);515		    }catch(err){	516		    } 517		  }518	});519	520	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////521	522	//Handle GET Dao Blocks523	524	$(document).on('get-dao-block-init', function(e, block, dao){	525		var options = IGRP_BLOCKLY_DROPS.daos[dao];526		var dropdown = new Blockly.FieldDropdown(options, function(option) {	527			this.sourceBlock_.updateShape_(option);    528	    });	529		block.setColour(160);530	    block.appendDummyInput().appendField("get "+dao).appendField(dropdown, 'DAO_FIELD')531		     .appendField(new Blockly.FieldImage(path+"/core/blockly/blockly/media/dao.svg",15,15,"*"));532	    block.setInputsInline(true);533	    block.setOutput(true);534		block.mutationToDom =  function() {535		    var container = document.createElement('mutation');536		    var itemInput = this.getFieldValue('DAO_FIELD');537		    container.setAttribute('hover_type', itemInput);538		    return container; 539		},540541		block.domToMutation = function(xmlElement) {542		    var itemInput = xmlElement.getAttribute('hover_type');543		    this.updateShape_(itemInput);  544		},545		546		block.updateShape_  = function(input_type) {		 547		 	var strSplit    = input_type.split('::'),548				type        = strSplit[0],549				val 	    = strSplit[1],550		        inputExists = this.getInput('dao_rela'); 551		    if (type.includes("_FK#")) {552		      if (!inputExists) {553		        this.appendValueInput('dao_rela').setCheck();554		      }555		    }else556		    try{557		    	this.removeInput('dao_rela');558		    }catch(err){	559		    } 560		  }561	});562
...input.spec.js
Source:input.spec.js  
...14    }).then((result) => {15      expect(result.value).to.equal(string)16      done()17    })18    Swal.getInput().value = string19    Swal.clickConfirm()20  })21  it('input textarea', (done) => {22    Swal.fire({23      input: 'textarea',24      inputAutoTrim: false25    }).then((result) => {26      expect(result.value).to.equal('hola!')27      done()28    })29    // Enter should not submit but put a newline to the textarea30    triggerKeydownEvent(Swal.getInput(), 'Enter')31    Swal.getInput().value = 'hola!'32    Swal.clickConfirm()33  })34  it('input email + built-in email validation', (done) => {35    const invalidEmailAddress = 'blah-blah@zzz'36    const validEmailAddress = 'team+support+a.b@example.com'37    SwalWithoutAnimation.fire({ input: 'email' }).then((result) => {38      expect(result.value).to.equal(validEmailAddress)39      done()40    })41    Swal.getInput().value = invalidEmailAddress42    Swal.clickConfirm()43    setTimeout(() => {44      expect(isVisible(Swal.getValidationMessage())).to.be.true45      expect(Swal.getValidationMessage().textContent.indexOf('Invalid email address') !== -1).to.be.true46      Swal.getInput().value = validEmailAddress47      triggerKeydownEvent(Swal.getInput(), 'Enter')48    }, TIMEOUT)49  })50  it('input url + built-in url validation', (done) => {51    const invalidUrl = 'sweetalert2.github.io'52    const validUrl = 'https://sweetalert2.github.io/'53    SwalWithoutAnimation.fire({ input: 'url' }).then((result) => {54      expect(result.value).to.equal(validUrl)55      done()56    })57    Swal.getInput().value = invalidUrl58    Swal.clickConfirm()59    setTimeout(() => {60      expect(isVisible(Swal.getValidationMessage())).to.be.true61      expect(Swal.getValidationMessage().textContent.indexOf('Invalid URL') !== -1).to.be.true62      Swal.getInput().value = validUrl63      triggerKeydownEvent(Swal.getInput(), 'Enter')64    }, TIMEOUT)65  })66  it('input select', (done) => {67    const selected = 'dos'68    Swal.fire({69      input: 'select',70      inputOptions: { uno: 1, dos: 2 },71      inputPlaceholder: 'Choose a number'72    }).then((result) => {73      expect(result.value).to.equal(selected)74      done()75    })76    expect(Swal.getInput().value).to.equal('')77    const placeholderOption = Swal.getInput().querySelector('option')78    expect(placeholderOption.disabled).to.be.true79    expect(placeholderOption.selected).to.be.true80    expect(placeholderOption.textContent).to.equal('Choose a number')81    Swal.getInput().value = selected82    Swal.clickConfirm()83  })84  it('input select with optgroup and root options', (done) => {85    const selected = 'três ponto um'86    Swal.fire({87      input: 'select',88      inputOptions: { 'um': 1.0, 'dois': 2.0, 'três': { 'três ponto um': 3.1, 'três ponto dois': 3.2 } },89      inputPlaceholder: 'Choose an item'90    }).then((result) => {91      expect(result.value).to.equal(selected)92      done()93    })94    expect(Swal.getInput().value).to.equal('')95    const placeholderOption = Swal.getInput().querySelector('option')96    expect(placeholderOption.disabled).to.be.true97    expect(placeholderOption.selected).to.be.true98    expect(placeholderOption.textContent).to.equal('Choose an item')99    Swal.getInput().value = selected100    Swal.clickConfirm()101  })102  it('input select with only optgroups options', (done) => {103    const selected = 'três ponto dois'104    Swal.fire({105      input: 'select',106      inputOptions: { 'dois': { 'dois ponto um': 2.1, 'dois ponto dois': 2.2 }, 'três': { 'três ponto um': 3.1, 'três ponto dois': 3.2 } },107      inputPlaceholder: 'Choose an item'108    }).then((result) => {109      expect(result.value).to.equal(selected)110      done()111    })112    expect(Swal.getInput().value).to.equal('')113    const placeholderOption = Swal.getInput().querySelector('option')114    expect(placeholderOption.disabled).to.be.true115    expect(placeholderOption.selected).to.be.true116    expect(placeholderOption.textContent).to.equal('Choose an item')117    Swal.getInput().value = selected118    Swal.clickConfirm()119  })120  it('input select with inputOptions as Promise', (done) => {121    Swal.fire({122      input: 'select',123      inputOptions: Promise.resolve({ one: 1, two: 2 }),124      didOpen: () => {125        setTimeout(() => {126          Swal.getInput().value = 'one'127          expect(Swal.getInput().value).to.equal('one')128          done()129        }, TIMEOUT)130      }131    })132  })133  it('input select with inputOptions as object containing toPromise', (done) => {134    Swal.fire({135      input: 'select',136      inputOptions: {137        toPromise: () => Promise.resolve({ three: 3, four: 4 })138      },139      didOpen: () => {140        setTimeout(() => {141          Swal.getInput().value = 'three'142          expect(Swal.getInput().value).to.equal('three')143          done()144        }, TIMEOUT)145      }146    })147  })148  it('input text w/ inputPlaceholder as configuration', () => {149    Swal.fire({150      input: 'text',151      inputPlaceholder: 'placeholder text'152    })153    expect(Swal.getInput().value).to.equal('')154    expect(Swal.getInput().placeholder).to.equal('placeholder text')155  })156  it('input checkbox', (done) => {157    Swal.fire({ input: 'checkbox', inputAttributes: { name: 'test-checkbox' } }).then((result) => {158      expect(checkbox.getAttribute('name')).to.equal('test-checkbox')159      expect(result.value).to.equal(1)160      done()161    })162    const checkbox = $('.swal2-checkbox input')163    checkbox.checked = true164    Swal.clickConfirm()165  })166  it('input range', () => {167    Swal.fire({ input: 'range', inputAttributes: { min: 1, max: 10 }, inputValue: 5 })168    const input = Swal.getInput()169    const output = $('.swal2-range output')170    expect(input.getAttribute('min')).to.equal('1')171    expect(input.getAttribute('max')).to.equal('10')172    expect(input.value).to.equal('5')173    input.value = 10174    dispatchCustomEvent(input, 'input')175    expect(output.textContent).to.equal('10')176    input.value = 9177    dispatchCustomEvent(input, 'change')178    expect(output.textContent).to.equal('9')179  })180  it('input type "select", inputOptions Map', () => {181    const inputOptions = new Map()182    inputOptions.set(2, 'Richard Stallman')183    inputOptions.set(1, 'Linus Torvalds')184    SwalWithoutAnimation.fire({185      input: 'select',186      inputOptions,187      inputValue: 1188    })189    expect($('.swal2-select').querySelectorAll('option').length).to.equal(2)190    expect($('.swal2-select option:nth-child(1)').innerHTML).to.equal('Richard Stallman')191    expect($('.swal2-select option:nth-child(1)').value).to.equal('2')192    expect($('.swal2-select option:nth-child(2)').innerHTML).to.equal('Linus Torvalds')193    expect($('.swal2-select option:nth-child(2)').value).to.equal('1')194    expect($('.swal2-select option:nth-child(2)').selected).to.equal(true)195  })196  it('input type "select", inputOptions Map with optgroup and root options', () => {197    const inputOptions = new Map()198    inputOptions.set(2, 'Richard Stallman')199    inputOptions.set(1, 'Linus Torvalds')200    const optGroup1Options = new Map()201    optGroup1Options.set(100, 'jQuery')202    optGroup1Options.set(200, 'ReactJS')203    optGroup1Options.set(300, 'VueJS')204    inputOptions.set('Frameworks optgroup', optGroup1Options)205    SwalWithoutAnimation.fire({206      input: 'select',207      inputOptions,208      inputValue: 1209    })210    expect($('.swal2-select').querySelectorAll('option').length).to.equal(5)211    expect($('.swal2-select').querySelectorAll('optgroup').length).to.equal(1)212    expect($('.swal2-select option:nth-child(1)').innerHTML).to.equal('Richard Stallman')213    expect($('.swal2-select option:nth-child(1)').value).to.equal('2')214    expect($('.swal2-select option:nth-child(2)').innerHTML).to.equal('Linus Torvalds')215    expect($('.swal2-select option:nth-child(2)').value).to.equal('1')216    expect($('.swal2-select option:nth-child(2)').selected).to.equal(true)217    expect($('.swal2-select optgroup option:nth-child(1)').innerHTML).to.equal('jQuery')218    expect($('.swal2-select optgroup option:nth-child(1)').value).to.equal('100')219    expect($('.swal2-select optgroup option:nth-child(2)').innerHTML).to.equal('ReactJS')220    expect($('.swal2-select optgroup option:nth-child(2)').value).to.equal('200')221    expect($('.swal2-select optgroup option:nth-child(3)').innerHTML).to.equal('VueJS')222    expect($('.swal2-select optgroup option:nth-child(3)').value).to.equal('300')223  })224  it('input type "select", inputOptions Map with only optgroup options', () => {225    const inputOptions = new Map()226    const frameworkOptGroupOptions = new Map()227    frameworkOptGroupOptions.set('100', 'jQuery')228    frameworkOptGroupOptions.set('200', 'ReactJS')229    frameworkOptGroupOptions.set('300', 'VueJS')230    inputOptions.set('Frameworks optgroup', frameworkOptGroupOptions)231    const libOptGroupOptions = new Map()232    libOptGroupOptions.set('1000', 'SweetAlert2')233    libOptGroupOptions.set('2000', 'Bootstrap4')234    inputOptions.set('Library optgroup', libOptGroupOptions)235    SwalWithoutAnimation.fire({236      input: 'select',237      inputOptions,238      inputValue: '1000'239    })240    expect($('.swal2-select').querySelectorAll('option').length).to.equal(5)241    expect($('.swal2-select').querySelectorAll('optgroup').length).to.equal(2)242    expect($('.swal2-select optgroup:nth-child(1) option:nth-child(1)').innerHTML).to.equal('jQuery')243    expect($('.swal2-select optgroup:nth-child(1) option:nth-child(1)').value).to.equal('100')244    expect($('.swal2-select optgroup:nth-child(1) option:nth-child(2)').innerHTML).to.equal('ReactJS')245    expect($('.swal2-select optgroup:nth-child(1) option:nth-child(2)').value).to.equal('200')246    expect($('.swal2-select optgroup:nth-child(1) option:nth-child(3)').innerHTML).to.equal('VueJS')247    expect($('.swal2-select optgroup:nth-child(1) option:nth-child(3)').value).to.equal('300')248    expect($('.swal2-select optgroup:nth-child(2) option:nth-child(1)').innerHTML).to.equal('SweetAlert2')249    expect($('.swal2-select optgroup:nth-child(2) option:nth-child(1)').value).to.equal('1000')250    expect($('.swal2-select optgroup:nth-child(2) option:nth-child(1)').selected).to.equal(true)251    expect($('.swal2-select optgroup:nth-child(2) option:nth-child(2)').innerHTML).to.equal('Bootstrap4')252    expect($('.swal2-select optgroup:nth-child(2) option:nth-child(2)').value).to.equal('2000')253  })254  it('input type "radio", inputOptions Map', () => {255    const inputOptions = new Map()256    inputOptions.set(2, 'Richard Stallman')257    inputOptions.set(1, 'Linus Torvalds')258    Swal.fire({259      input: 'radio',260      inputOptions,261      inputValue: 1262    })263    expect($('.swal2-radio').querySelectorAll('label').length).to.equal(2)264    expect($('.swal2-radio label:nth-child(1)').textContent).to.equal('Richard Stallman')265    expect($('.swal2-radio label:nth-child(1) input').value).to.equal('2')266    expect($('.swal2-radio label:nth-child(2)').textContent).to.equal('Linus Torvalds')267    expect($('.swal2-radio label:nth-child(2) input').value).to.equal('1')268    expect($('.swal2-radio label:nth-child(2) input').checked).to.equal(true)269  })270  it('input radio', () => {271    Swal.fire({272      input: 'radio',273      inputOptions: {274        one: 'one',275        two: 'two'276      }277    })278    expect($('.swal2-radio').querySelectorAll('label').length).to.equal(2)279    expect($('.swal2-radio').querySelectorAll('input[type="radio"]').length).to.equal(2)280  })281  it('popup should expand and shrink accordingly to textarea width', (done) => {282    SwalWithoutAnimation.fire({283      input: 'textarea',284    })285    Swal.getInput().style.width = '600px'286    setTimeout(() => {287      expect(Swal.getPopup().style.width).to.equal('696px')288      Swal.getInput().style.width = '100px'289      setTimeout(() => {290        expect(Swal.getPopup().style.width).to.equal('')291        done()292      })293    })294  })295  it('returnInputValueOnDeny: true should pass the input value as result.value', (done) => {296    SwalWithoutAnimation.fire({297      input: 'text',298      inputValue: 'returnInputValueOnDeny',299      returnInputValueOnDeny: true,300    }).then((result) => {301      expect(result).to.eql({302        value: 'returnInputValueOnDeny',303        isConfirmed: false,304        isDenied: true,305        isDismissed: false,306      })307      done()308    })309    Swal.clickDeny()310  })311  it('disable/enable input', () => {312    Swal.fire('(disable/enable)Input should not fail if there is no input')313    Swal.disableInput()314    Swal.enableInput()315    Swal.fire({316      input: 'text'317    })318    Swal.disableInput()319    expect(Swal.getInput().disabled).to.be.true320    Swal.enableInput()321    expect(Swal.getInput().disabled).to.be.false322    Swal.fire({323      input: 'radio',324      inputOptions: {325        one: 'one',326        two: 'two'327      }328    })329    Swal.disableInput()330    toArray($('.swal2-radio').querySelectorAll('radio')).forEach((radio) => {331      expect(radio.disabled).to.be.true332    })333    Swal.enableInput()334    toArray($('.swal2-radio').querySelectorAll('radio')).forEach((radio) => {335      expect(radio.disabled).to.be.false336    })337  })338  it('should throw console error about unexpected type of InputOptions', () => {339    const spy = cy.spy(console, 'error')340    Swal.fire({ input: 'select', inputOptions: 'invalid-input-options' })341    expect(spy.calledWith('SweetAlert2: Unexpected type of inputOptions! Expected object, Map or Promise, got string')).to.be.true342  })343})344describe('Validation', () => {345  it('input.checkValidity()', (done) => {346    Swal.fire({347      input: 'tel',348      inputAttributes: {349        pattern: '[0-9]{3}-[0-9]{3}-[0-9]{4}'350      },351      validationMessage: 'Invalid phone number',352      customClass: {353        validationMessage: 'my-validation-message'354      },355    }).then(result => {356      expect(result.value).to.equal('123-456-7890')357      done()358    })359    Swal.getInput().value = 'blah-blah'360    Swal.clickConfirm()361    setTimeout(() => {362      expect(Swal.getConfirmButton().disabled).to.be.false363      expect(Swal.getDenyButton().disabled).to.be.false364      expect(Swal.getCancelButton().disabled).to.be.false365      expect(isVisible(Swal.getValidationMessage())).to.be.true366      expect(Swal.getValidationMessage().textContent).to.equal('Invalid phone number')367      expect(Swal.getValidationMessage().classList.contains('my-validation-message')).to.be.true368      Swal.getInput().value = '123-456-7890'369      Swal.clickConfirm()370    }, TIMEOUT)371  })372  it('validation message', (done) => {373    const inputValidator = (value) => Promise.resolve(!value && 'no falsy values')374    SwalWithoutAnimation.fire({ input: 'text', inputValidator })375    expect(isHidden(Swal.getValidationMessage())).to.be.true376    setTimeout(() => {377      const initialModalHeight = Swal.getPopup().offsetHeight378      Swal.clickConfirm()379      setTimeout(() => {380        expect(isVisible(Swal.getValidationMessage())).to.be.true381        expect(Swal.getValidationMessage().textContent).to.equal('no falsy values')382        expect(Swal.getInput().getAttribute('aria-invalid')).to.equal('true')383        expect(Swal.getPopup().offsetHeight > initialModalHeight).to.be.true384        Swal.getInput().value = 'blah-blah'385        // setting the value programmatically will not trigger the 'input' event,386        // doing that manually387        const event = document.createEvent('Event')388        event.initEvent('input', true, true)389        Swal.getInput().dispatchEvent(event)390        expect(isHidden(Swal.getValidationMessage())).to.be.true391        expect(Swal.getInput().getAttribute('aria-invalid')).to.be.null392        expect(Swal.getPopup().offsetHeight === initialModalHeight).to.be.true393        done()394      }, TIMEOUT)395    }, TIMEOUT)396  })397  it('validation message with object containing toPromise', (done) => {398    SwalWithoutAnimation.fire({399      input: 'text',400      inputValidator: (value) => ({401        toPromise: () => Promise.resolve(!value && 'no falsy values')402      })403    })404    setTimeout(() => {405      Swal.clickConfirm()...input.js
Source:input.js  
...15  }).then((result) => {16    assert.equal(result.value, string)17    done()18  })19  Swal.getInput().value = string20  Swal.clickConfirm()21})22QUnit.test('input textarea', (assert) => {23  const done = assert.async()24  Swal.fire({25    input: 'textarea',26    inputAutoTrim: false27  }).then((result) => {28    assert.equal(result.value, 'hola!')29    done()30  })31  // Enter should not submit but put a newline to the textarea32  triggerKeydownEvent(Swal.getInput(), 'Enter')33  Swal.getInput().value = 'hola!'34  Swal.clickConfirm()35})36QUnit.test('input email + built-in email validation', (assert) => {37  const done = assert.async()38  const invalidEmailAddress = 'blah-blah@zzz'39  const validEmailAddress = 'team+support+a.b@example.com'40  SwalWithoutAnimation.fire({ input: 'email' }).then((result) => {41    assert.equal(result.value, validEmailAddress)42    done()43  })44  Swal.getInput().value = invalidEmailAddress45  Swal.clickConfirm()46  setTimeout(() => {47    assert.ok(isVisible(Swal.getValidationMessage()))48    assert.ok(Swal.getValidationMessage().textContent.indexOf('Invalid email address') !== -1)49    Swal.getInput().value = validEmailAddress50    triggerKeydownEvent(Swal.getInput(), 'Enter')51  }, TIMEOUT)52})53QUnit.test('input url + built-in url validation', (assert) => {54  const done = assert.async()55  const invalidUrl = 'sweetalert2.github.io'56  const validUrl = 'https://sweetalert2.github.io/'57  SwalWithoutAnimation.fire({ input: 'url' }).then((result) => {58    assert.equal(result.value, validUrl)59    done()60  })61  Swal.getInput().value = invalidUrl62  Swal.clickConfirm()63  setTimeout(() => {64    assert.ok(isVisible(Swal.getValidationMessage()))65    assert.ok(Swal.getValidationMessage().textContent.indexOf('Invalid URL') !== -1)66    Swal.getInput().value = validUrl67    triggerKeydownEvent(Swal.getInput(), 'Enter')68  }, TIMEOUT)69})70QUnit.test('input select', (assert) => {71  const done = assert.async()72  const selected = 'dos'73  Swal.fire({74    input: 'select',75    inputOptions: { uno: 1, dos: 2 },76    inputPlaceholder: 'Choose a number'77  }).then((result) => {78    assert.equal(result.value, selected)79    done()80  })81  assert.equal(Swal.getInput().value, '')82  const placeholderOption = Swal.getInput().querySelector('option')83  assert.ok(placeholderOption.disabled)84  assert.ok(placeholderOption.selected)85  assert.equal(placeholderOption.textContent, 'Choose a number')86  Swal.getInput().value = selected87  Swal.clickConfirm()88})89QUnit.test('input select with optgroup and root options', (assert) => {90  const done = assert.async()91  const selected = 'três ponto um'92  Swal.fire({93    input: 'select',94    inputOptions: { 'um': 1.0, 'dois': 2.0, 'três': { 'três ponto um': 3.1, 'três ponto dois': 3.2 } },95    inputPlaceholder: 'Choose an item'96  }).then((result) => {97    assert.equal(result.value, selected)98    done()99  })100  assert.equal(Swal.getInput().value, '')101  const placeholderOption = Swal.getInput().querySelector('option')102  assert.ok(placeholderOption.disabled)103  assert.ok(placeholderOption.selected)104  assert.equal(placeholderOption.textContent, 'Choose an item')105  Swal.getInput().value = selected106  Swal.clickConfirm()107})108QUnit.test('input select with only optgroups options', (assert) => {109  const done = assert.async()110  const selected = 'três ponto dois'111  Swal.fire({112    input: 'select',113    inputOptions: { 'dois': { 'dois ponto um': 2.1, 'dois ponto dois': 2.2 }, 'três': { 'três ponto um': 3.1, 'três ponto dois': 3.2 } },114    inputPlaceholder: 'Choose an item'115  }).then((result) => {116    assert.equal(result.value, selected)117    done()118  })119  assert.equal(Swal.getInput().value, '')120  const placeholderOption = Swal.getInput().querySelector('option')121  assert.ok(placeholderOption.disabled)122  assert.ok(placeholderOption.selected)123  assert.equal(placeholderOption.textContent, 'Choose an item')124  Swal.getInput().value = selected125  Swal.clickConfirm()126})127QUnit.test('input select with inputOptions as Promise', (assert) => {128  const done = assert.async()129  Swal.fire({130    input: 'select',131    inputOptions: Promise.resolve({ one: 1, two: 2 }),132    didOpen: () => {133      setTimeout(() => {134        Swal.getInput().value = 'one'135        assert.equal(Swal.getInput().value, 'one')136        done()137      }, TIMEOUT)138    }139  })140})141QUnit.test('input select with inputOptions as object containing toPromise', (assert) => {142  const done = assert.async()143  Swal.fire({144    input: 'select',145    inputOptions: {146      toPromise: () => Promise.resolve({ three: 3, four: 4 })147    },148    didOpen: () => {149      setTimeout(() => {150        Swal.getInput().value = 'three'151        assert.equal(Swal.getInput().value, 'three')152        done()153      }, TIMEOUT)154    }155  })156})157QUnit.test('input text w/ inputPlaceholder as configuration', (assert) => {158  const done = assert.async()159  Swal.fire({160    input: 'text',161    inputPlaceholder: 'placeholder text'162  })163  assert.equal(Swal.getInput().value, '')164  assert.equal(Swal.getInput().placeholder, 'placeholder text')165  done()166})167QUnit.test('input checkbox', (assert) => {168  const done = assert.async()169  Swal.fire({ input: 'checkbox', inputAttributes: { name: 'test-checkbox' } }).then((result) => {170    assert.equal(checkbox.getAttribute('name'), 'test-checkbox')171    assert.equal(result.value, '1')172    done()173  })174  const checkbox = $('.swal2-checkbox input')175  checkbox.checked = true176  Swal.clickConfirm()177})178QUnit.test('input range', (assert) => {179  Swal.fire({ input: 'range', inputAttributes: { min: 1, max: 10 }, inputValue: 5 })180  const input = Swal.getInput()181  const output = $('.swal2-range output')182  assert.equal(input.getAttribute('min'), '1')183  assert.equal(input.getAttribute('max'), '10')184  assert.equal(input.value, '5')185  if (!isIE) { // TODO (@limonte): make IE happy186    input.value = 10187    dispatchCustomEvent(input, 'input')188    assert.equal(output.textContent, '10')189    input.value = 9190    dispatchCustomEvent(input, 'change')191    assert.equal(output.textContent, '9')192  }193})194QUnit.test('input type "select", inputOptions Map', (assert) => {195  const inputOptions = new Map()196  inputOptions.set(2, 'Richard Stallman')197  inputOptions.set(1, 'Linus Torvalds')198  SwalWithoutAnimation.fire({199    input: 'select',200    inputOptions,201    inputValue: 1202  })203  assert.equal($('.swal2-select').querySelectorAll('option').length, 2)204  assert.equal($('.swal2-select option:nth-child(1)').innerHTML, 'Richard Stallman')205  assert.equal($('.swal2-select option:nth-child(1)').value, '2')206  assert.equal($('.swal2-select option:nth-child(2)').innerHTML, 'Linus Torvalds')207  assert.equal($('.swal2-select option:nth-child(2)').value, '1')208  assert.equal($('.swal2-select option:nth-child(2)').selected, true)209})210QUnit.test('input type "select", inputOptions Map with optgroup and root options', (assert) => {211  const inputOptions = new Map()212  inputOptions.set(2, 'Richard Stallman')213  inputOptions.set(1, 'Linus Torvalds')214  const optGroup1Options = new Map()215  optGroup1Options.set(100, 'jQuery')216  optGroup1Options.set(200, 'ReactJS')217  optGroup1Options.set(300, 'VueJS')218  inputOptions.set('Frameworks optgroup', optGroup1Options)219  SwalWithoutAnimation.fire({220    input: 'select',221    inputOptions,222    inputValue: 1223  })224  assert.equal($('.swal2-select').querySelectorAll('option').length, 5)225  assert.equal($('.swal2-select').querySelectorAll('optgroup').length, 1)226  assert.equal($('.swal2-select option:nth-child(1)').innerHTML, 'Richard Stallman')227  assert.equal($('.swal2-select option:nth-child(1)').value, '2')228  assert.equal($('.swal2-select option:nth-child(2)').innerHTML, 'Linus Torvalds')229  assert.equal($('.swal2-select option:nth-child(2)').value, '1')230  assert.equal($('.swal2-select option:nth-child(2)').selected, true)231  assert.equal($('.swal2-select optgroup option:nth-child(1)').innerHTML, 'jQuery')232  assert.equal($('.swal2-select optgroup option:nth-child(1)').value, '100')233  assert.equal($('.swal2-select optgroup option:nth-child(2)').innerHTML, 'ReactJS')234  assert.equal($('.swal2-select optgroup option:nth-child(2)').value, '200')235  assert.equal($('.swal2-select optgroup option:nth-child(3)').innerHTML, 'VueJS')236  assert.equal($('.swal2-select optgroup option:nth-child(3)').value, '300')237})238QUnit.test('input type "select", inputOptions Map with only optgroup options', (assert) => {239  const inputOptions = new Map()240  const frameworkOptGroupOptions = new Map()241  frameworkOptGroupOptions.set('100', 'jQuery')242  frameworkOptGroupOptions.set('200', 'ReactJS')243  frameworkOptGroupOptions.set('300', 'VueJS')244  inputOptions.set('Frameworks optgroup', frameworkOptGroupOptions)245  const libOptGroupOptions = new Map()246  libOptGroupOptions.set('1000', 'SweetAlert2')247  libOptGroupOptions.set('2000', 'Bootstrap4')248  inputOptions.set('Library optgroup', libOptGroupOptions)249  SwalWithoutAnimation.fire({250    input: 'select',251    inputOptions,252    inputValue: '1000'253  })254  assert.equal($('.swal2-select').querySelectorAll('option').length, 5)255  assert.equal($('.swal2-select').querySelectorAll('optgroup').length, 2)256  assert.equal($('.swal2-select optgroup:nth-child(1) option:nth-child(1)').innerHTML, 'jQuery')257  assert.equal($('.swal2-select optgroup:nth-child(1) option:nth-child(1)').value, '100')258  assert.equal($('.swal2-select optgroup:nth-child(1) option:nth-child(2)').innerHTML, 'ReactJS')259  assert.equal($('.swal2-select optgroup:nth-child(1) option:nth-child(2)').value, '200')260  assert.equal($('.swal2-select optgroup:nth-child(1) option:nth-child(3)').innerHTML, 'VueJS')261  assert.equal($('.swal2-select optgroup:nth-child(1) option:nth-child(3)').value, '300')262  assert.equal($('.swal2-select optgroup:nth-child(2) option:nth-child(1)').innerHTML, 'SweetAlert2')263  assert.equal($('.swal2-select optgroup:nth-child(2) option:nth-child(1)').value, '1000')264  assert.equal($('.swal2-select optgroup:nth-child(2) option:nth-child(1)').selected, true)265  assert.equal($('.swal2-select optgroup:nth-child(2) option:nth-child(2)').innerHTML, 'Bootstrap4')266  assert.equal($('.swal2-select optgroup:nth-child(2) option:nth-child(2)').value, '2000')267})268QUnit.test('input type "radio", inputOptions Map', (assert) => {269  const inputOptions = new Map()270  inputOptions.set(2, 'Richard Stallman')271  inputOptions.set(1, 'Linus Torvalds')272  Swal.fire({273    input: 'radio',274    inputOptions,275    inputValue: 1276  })277  assert.equal($('.swal2-radio').querySelectorAll('label').length, 2)278  assert.equal($('.swal2-radio label:nth-child(1)').textContent, 'Richard Stallman')279  assert.equal($('.swal2-radio label:nth-child(1) input').value, '2')280  assert.equal($('.swal2-radio label:nth-child(2)').textContent, 'Linus Torvalds')281  assert.equal($('.swal2-radio label:nth-child(2) input').value, '1')282  assert.equal($('.swal2-radio label:nth-child(2) input').checked, true)283})284QUnit.test('input radio', (assert) => {285  Swal.fire({286    input: 'radio',287    inputOptions: {288      one: 'one',289      two: 'two'290    }291  })292  assert.equal($('.swal2-radio').querySelectorAll('label').length, 2)293  assert.equal($('.swal2-radio').querySelectorAll('input[type="radio"]').length, 2)294})295QUnit.test('Swal.getInput() should be available in .then()', (assert) => {296  const done = assert.async()297  SwalWithoutAnimation.fire({298    input: 'text',299  }).then(() => {300    assert.ok(Swal.getInput())301    done()302  })303  Swal.close()304})305QUnit.test('Swal.getInput() should return null when a popup is disposed', (assert) => {306  const done = assert.async()307  SwalWithoutAnimation.fire({308    input: 'text',309    didClose: () => {310      setTimeout(() => {311        assert.notOk(Swal.getInput())312        done()313      }, TIMEOUT)314    }315  })316  Swal.close()317})318QUnit.test('popup should expand and shrink accordingly to textarea width', (assert) => {319  const done = assert.async()320  SwalWithoutAnimation.fire({321    input: 'textarea',322  })323  Swal.getInput().style.width = '600px'324  setTimeout(() => {325    assert.equal(Swal.getPopup().style.width, '696px')326    Swal.getInput().style.width = '100px'327    setTimeout(() => {328      assert.equal(Swal.getPopup().style.width, '')329      done()330    })331  })332})333QUnit.test('returnInputValueOnDeny: true should pass the input value as result.value', (assert) => {334  const done = assert.async()335  SwalWithoutAnimation.fire({336    input: 'text',337    inputValue: 'returnInputValueOnDeny',338    returnInputValueOnDeny: true,339  }).then((result) => {340    assert.deepEqual(result, {...CanvasDateInput.test.js
Source:CanvasDateInput.test.js  
...36  return result37}38function renderAndDirtyInput(inputValue, overrides = {}) {39  const result = renderInput(overrides)40  const input = result.getInput()41  fireEvent.change(input, {target: {value: inputValue}})42  return result43}44const oldLocale = moment.locale()45beforeEach(() => {46  // Not directly at midnight so we can test the dates coming from this component are set to the47  // beginning of the day and don't retain the time.48  MockDate.set('2020-05-19T00:42:00Z', 0)49  moment.locale('en-us')50})51afterEach(() => {52  MockDate.reset()53  moment.locale(oldLocale)54})55describe('clean input state', () => {56  it('displays an empty input value when the selectedDate prop is initially null', () => {57    const {getInput} = renderInput()58    expect(getInput().value).toBe('')59  })60  it('displays the formatted date when the initial date is not null', () => {61    const now = new Date()62    const formatter = jest.fn(() => 'formatted date')63    const {getInput} = renderInput({selectedDate: now, formatDate: formatter})64    expect(formatter).toHaveBeenCalledWith(now)65    expect(getInput().value).toBe('formatted date')66  })67  it('resets the input when the selectedDate changes value', () => {68    const now = moment.tz('UTC')69    const {props, rerender, getInput} = renderInput({selectedDate: now.toDate()})70    props.selectedDate = now.add(1, 'day').toDate()71    rerender(<CanvasDateInput {...props} />)72    expect(getInput().value).toBe(now.toISOString())73  })74  it('resets the input when the selectedDate changes from null to a date', () => {75    const now = moment.tz('UTC')76    const {props, rerender, getInput} = renderInput()77    props.selectedDate = now.toDate()78    rerender(<CanvasDateInput {...props} />)79    expect(getInput().value).toBe(now.toISOString())80  })81  it('clears the input when the selectedDate changes to null', () => {82    const now = moment.tz('UTC')83    const {props, rerender, getInput} = renderInput({selectedDate: now.toDate()})84    props.selectedDate = null85    rerender(<CanvasDateInput {...props} />)86    expect(getInput().value).toBe('')87  })88})89describe('choosing a day on the calendar', () => {90  it('selects the date when clicked', () => {91    const {props, getByText, getInput} = renderInput()92    fireEvent.click(getInput())93    const button15 = getByText('15').closest('button')94    fireEvent.click(button15)95    expect(props.onSelectedDateChange).toHaveBeenCalledWith(new Date('2020-05-15'))96  })97  it('hides the calendar when clicked', () => {98    const {getByText, queryByText, getInput} = renderInput()99    fireEvent.click(getInput())100    const button15 = getByText('15').closest('button')101    fireEvent.click(button15)102    expect(queryByText('15')).toBeNull()103  })104  it('selects the first of the month on ArrowDown if selectedDate is null', () => {105    const {props, getInput} = renderInput()106    fireEvent.click(getInput())107    fireEvent.keyDown(getInput(), {key: 'ArrowDown', code: 40, keyCode: 40})108    expect(props.onSelectedDateChange).toHaveBeenCalledWith(new Date('2020-05-01'))109  })110  it('selects the first of the month on up-arrow if selectedDate is null', () => {111    const {props, getInput} = renderInput()112    fireEvent.click(getInput())113    fireEvent.keyDown(getInput(), {key: 'ArrowUp', code: 38, keyCode: 38})114    expect(props.onSelectedDateChange).toHaveBeenCalledWith(new Date('2020-05-01'))115  })116  it('selects the next date on down-arrow', () => {117    const {props, getInput} = renderInput({selectedDate: new Date()})118    fireEvent.click(getInput())119    fireEvent.keyDown(getInput(), {key: 'ArrowDown', code: 40, keyCode: 40})120    expect(props.onSelectedDateChange).toHaveBeenCalledWith(new Date('2020-05-20'))121  })122  it('selects the previous date on up-arrow', () => {123    const {props, getInput} = renderInput({selectedDate: new Date()})124    fireEvent.click(getInput())125    fireEvent.keyDown(getInput(), {key: 'ArrowUp', code: 38, keyCode: 38})126    expect(props.onSelectedDateChange).toHaveBeenCalledWith(new Date('2020-05-18'))127  })128})129describe('dirty input state', () => {130  it('resets the input when selectedDate changes to a new date', () => {131    const {props, rerender, getInput} = renderAndDirtyInput('asdf')132    expect(getInput().value).toBe('asdf')133    const newDate = new Date()134    props.selectedDate = new Date()135    rerender(<CanvasDateInput {...props} />)136    expect(getInput().value).toBe(newDate.toISOString())137  })138  it('resets the input when the selectedDate changes to null', () => {139    const {props, rerender, getInput} = renderAndDirtyInput('asdf', {selectedDate: new Date()})140    expect(getInput().value).toBe('asdf')141    props.selectedDate = null142    rerender(<CanvasDateInput {...props} />)143    expect(getInput().value).toBe('')144  })145  it('calls onSelectedDateChange with parsed date when the input blurs and sets the date input', () => {146    const {props, getInput} = renderAndDirtyInput('May 20')147    const newDate = new Date('2020-05-20')148    fireEvent.blur(getInput())149    expect(props.onSelectedDateChange).toHaveBeenCalledWith(newDate)150    expect(getInput().value).toBe(newDate.toISOString())151  })152  it('calls onSelectedDateChange with on blur and garbage input, and clears the input', () => {153    const {props, getInput} = renderAndDirtyInput('asdf')154    fireEvent.blur(getInput())155    expect(props.onSelectedDateChange).toHaveBeenCalledWith(null)156    expect(getInput().value).toBe('')157  })158})159describe('rendered month', () => {160  it('renders the proper 42 days based on the rendered month', () => {161    const {getAllByText, getInput} = renderInput()162    fireEvent.click(getInput())163    expect(getAllByText('25')).toHaveLength(1)164    expect(getAllByText('26')).toHaveLength(2)165    expect(getAllByText('6')).toHaveLength(2)166    expect(getAllByText('7')).toHaveLength(1)167  })168  it('renders the month for today when selectedDate is initially null', () => {169    const {getByText, getInput} = renderInput()170    fireEvent.click(getInput())171    expect(getByText('May')).toBeInTheDocument()172  })173  it('renders the month for the initial selectedDate', () => {174    const {getByText, getInput} = renderInput({selectedDate: new Date('2020-03-15')})175    fireEvent.click(getInput())176    expect(getByText('March')).toBeInTheDocument()177  })178  it('allows the rendered month to be incremented', () => {179    const {getByText, getInput} = renderInput()180    fireEvent.click(getInput())181    fireEvent.click(getByText('Next month'))182    expect(getByText('June')).toBeInTheDocument()183  })184  it('allows the rendered month to be decremented', () => {185    const {getByText, getInput} = renderInput()186    fireEvent.click(getInput())187    fireEvent.click(getByText('Previous month'))188    expect(getByText('April')).toBeInTheDocument()189  })190  it('resets the rendered date to the selectedDate when the selectedDate changes', () => {191    const {getByText, getInput} = renderInput()192    fireEvent.click(getInput())193    fireEvent.click(getByText('Next month'))194    fireEvent.change(getInput(), {target: {value: 'April 20'}})195    expect(getByText('April')).toBeInTheDocument()196  })197})198describe('error messages', () => {199  it('shows an error message if the input date is unparseable', () => {200    const {getByText} = renderAndDirtyInput('asdf')201    expect(getByText('Invalid Date')).toBeInTheDocument()202  })203  it('clears error messages when the selectedDate changes', () => {204    const {props, rerender, queryByText} = renderAndDirtyInput('asdf')205    props.selectedDate = new Date()206    rerender(<CanvasDateInput {...props} />)207    expect(queryByText('Invalid Date')).toBeNull()208  })209  it('clears error messages when a day is clicked', () => {210    const date = new Date()211    const {getByText, queryByText} = renderAndDirtyInput('asdf', {selectedDate: date})212    fireEvent.click(getByText('15'))213    expect(queryByText('Invalid Date')).toBeNull()214  })215  it('clears error messages even when selectedDay is clicked', () => {216    const date = new Date()217    const {getByText, queryByText} = renderAndDirtyInput('asdf', {selectedDate: date})218    fireEvent.click(getByText('20'))219    expect(queryByText('Invalid Date')).toBeNull()220  })221  it('clears error messages when the input changes to an empty string', () => {222    const {getInput, queryByText} = renderAndDirtyInput('asdf')223    fireEvent.change(getInput(), {target: {value: ''}})224    expect(queryByText('Invalid Date')).toBeNull()225  })226})227describe('messages', () => {228  it('shows the specified messages', () => {229    const {getByText} = renderInput({230      messages: [{type: 'hint', text: 'my what an interesting date'}]231    })232    expect(getByText('my what an interesting date')).toBeInTheDocument()233  })234  it('shows a running result when requested', () => {235    const {getByText} = renderAndDirtyInput('sat', {withRunningValue: true})236    // The Saturday after our "current date" is 5/23/2020237    expect(getByText('2020-05-23T00:00:00.000Z')).toBeInTheDocument()238  })239})240describe('locales', () => {241  it('renders the month string according to the locale', () => {242    moment.locale('fr')243    const {getByText, getInput} = renderInput({selectedDate: new Date()})244    fireEvent.click(getInput())245    expect(getByText('mai')).toBeInTheDocument()246  })247  it('renders Sunday as the first day of the week in the american locale', () => {248    const {getByText, getInput} = renderInput({selectedDate: new Date()})249    fireEvent.click(getInput())250    const sunday = getByText('Su')251    const headerRow = sunday.closest('tr')252    const sundayHeader = sunday.closest('th')253    expect(headerRow.children[0]).toBe(sundayHeader)254  })255  it('renders Monday as the first day of the week in french locale', () => {256    moment.locale('fr')257    const {getByText, getInput} = renderInput({selectedDate: new Date()})258    fireEvent.click(getInput())259    const lundi = getByText('lu')260    const headerRow = lundi.closest('tr')261    const lundiHeader = lundi.closest('th')262    expect(headerRow.children[0]).toBe(lundiHeader)263  })...dynamic-binding.test.js
Source:dynamic-binding.test.js  
...29        <span>text content</span>30      </Form>31    );32    const wrapper = mount(<Test mode />);33    getInput(wrapper, '#text').simulate('change', { target: { value: '123' } });34    wrapper.setProps({ mode: false });35    expect(getInput(wrapper, '#number').getDOMNode().value).toBe('123');36    expect(form.getFieldValue('name')).toBe('123');37    getInput(wrapper, '#number').simulate('change', { target: { value: '456' } });38    wrapper.setProps({ mode: true });39    expect(getInput(wrapper, '#text').getDOMNode().value).toBe('456');40    expect(form.getFieldValue('name')).toBe('456');41    const values = await form.validateFields();42    expect(values.name).toBe('456');43  });44  // [Legacy] We do not remove value in Field Form45  it('hidden input', async () => {46    let form;47    const Test = ({ mode }) => (48      <Form49        ref={instance => {50          form = instance;51        }}52      >53        <span>text content</span>54        {mode ? (55          <Field name="input1">56            <Input id="text1" />57          </Field>58        ) : null}59        <span>text content</span>60        <span>text content</span>61        <span>text content</span>62        {mode ? (63          <Field name="input2">64            <Input id="text2" />65          </Field>66        ) : null}67        <span>text content</span>68      </Form>69    );70    const wrapper = mount(<Test mode />);71    getInput(wrapper, '#text1').simulate('change', { target: { value: '123' } });72    getInput(wrapper, '#text2').simulate('change', { target: { value: '456' } });73    expect(getInput(wrapper, '#text1').getDOMNode().value).toBe('123');74    expect(getInput(wrapper, '#text2').getDOMNode().value).toBe('456');75    expect(form.getFieldValue('input1')).toBe('123');76    expect(form.getFieldValue('input2')).toBe('456');77    // Different with `rc-form`78    wrapper.setProps({ mode: false });79    expect(form.getFieldValue('input1')).toBeTruthy();80    expect(form.getFieldValue('input2')).toBeTruthy();81    wrapper.setProps({ mode: true });82    expect(getInput(wrapper, '#text1').getDOMNode().value).toBe('123');83    expect(getInput(wrapper, '#text2').getDOMNode().value).toBe('456');84    expect(form.getFieldValue('input1')).toBe('123');85    expect(form.getFieldValue('input2')).toBe('456');86    getInput(wrapper, '#text1').simulate('change', { target: { value: '789' } });87    expect(getInput(wrapper, '#text1').getDOMNode().value).toBe('789');88    expect(getInput(wrapper, '#text2').getDOMNode().value).toBe('456');89    expect(form.getFieldValue('input1')).toBe('789');90    expect(form.getFieldValue('input2')).toBe('456');91    const values = await form.validateFields();92    expect(values.input1).toBe('789');93    expect(values.input2).toBe('456');94  });95  it('nested fields', async () => {96    let form;97    const Test = ({ mode }) => (98      <Form99        ref={instance => {100          form = instance;101        }}102      >103        {mode ? (104          <Field name={['name', 'xxx']}>105            <Input id="text" />106          </Field>107        ) : null}108        <span>text content</span>109        {mode ? null : (110          <Field name={['name', 'xxx']}>111            <Input id="number" type="number" />112          </Field>113        )}114      </Form>115    );116    const wrapper = mount(<Test mode />);117    getInput(wrapper, '#text').simulate('change', { target: { value: '123' } });118    wrapper.setProps({ mode: false });119    expect(getInput(wrapper, '#number').getDOMNode().value).toBe('123');120    expect(form.getFieldValue(['name', 'xxx'])).toBe('123');121    getInput(wrapper, '#number').simulate('change', { target: { value: '456' } });122    wrapper.setProps({ mode: true });123    expect(getInput(wrapper, '#text').getDOMNode().value).toBe('456');124    expect(form.getFieldValue(['name', 'xxx'])).toBe('456');125    const values = await form.validateFields();126    expect(values.name.xxx).toBe('456');127  });128  it('input with different keys', async () => {129    let form;130    const Test = ({ mode }) => (131      <Form132        ref={instance => {133          form = instance;134        }}135      >136        {mode ? (137          <Field name="name">138            <Input key="text" id="text" />139          </Field>140        ) : null}141        {mode ? null : (142          <Field name="name">143            <Input key="number" id="number" type="number" />144          </Field>145        )}146      </Form>147    );148    const wrapper = mount(<Test mode />);149    getInput(wrapper, '#text').simulate('change', { target: { value: '123' } });150    wrapper.setProps({ mode: false });151    expect(getInput(wrapper, '#number').getDOMNode().value).toBe('123');152    expect(form.getFieldValue('name')).toBe('123');153    getInput(wrapper, '#number').simulate('change', { target: { value: '456' } });154    wrapper.setProps({ mode: true });155    expect(getInput(wrapper, '#text').getDOMNode().value).toBe('456');156    expect(form.getFieldValue('name')).toBe('456');157    const values = await form.validateFields();158    expect(values.name).toBe('456');159  });160  it('submit without removed fields', async () => {161    // [Legacy] Since we don't remove values, this test is no need anymore.162  });163  it('reset fields', async () => {164    let form;165    const Test = ({ mode }) => (166      <Form167        ref={instance => {168          form = instance;169        }}170      >171        <span>text content</span>172        {mode ? (173          <Field name="input1">174            <Input id="text1" />175          </Field>176        ) : null}177        <span>text content</span>178        <span>text content</span>179        <span>text content</span>180        {mode ? (181          <Field name="input2">182            <Input id="text2" />183          </Field>184        ) : null}185        <span>text content</span>186      </Form>187    );188    const wrapper = mount(<Test mode />);189    getInput(wrapper, '#text1').simulate('change', { target: { value: '123' } });190    getInput(wrapper, '#text2').simulate('change', { target: { value: '456' } });191    expect(getInput(wrapper, '#text1').getDOMNode().value).toBe('123');192    expect(getInput(wrapper, '#text2').getDOMNode().value).toBe('456');193    expect(form.getFieldValue('input1')).toBe('123');194    expect(form.getFieldValue('input2')).toBe('456');195    // Different with `rc-form` test196    wrapper.setProps({ mode: false });197    expect(form.getFieldValue('input1')).toBeTruthy();198    expect(form.getFieldValue('input2')).toBeTruthy();199    form.resetFields();200    wrapper.setProps({ mode: true });201    expect(getInput(wrapper, '#text1').getDOMNode().value).toBe('');202    expect(getInput(wrapper, '#text2').getDOMNode().value).toBe('');203    expect(form.getFieldValue('input1')).toBe(undefined);204    expect(form.getFieldValue('input2')).toBe(undefined);205    getInput(wrapper, '#text1').simulate('change', { target: { value: '789' } });206    expect(getInput(wrapper, '#text1').getDOMNode().value).toBe('789');207    expect(getInput(wrapper, '#text2').getDOMNode().value).toBe('');208    expect(form.getFieldValue('input1')).toBe('789');209    expect(form.getFieldValue('input2')).toBe(undefined);210    getInput(wrapper, '#text2').simulate('change', { target: { value: '456' } });211    expect(getInput(wrapper, '#text2').getDOMNode().value).toBe('456');212    expect(form.getFieldValue('input2')).toBe('456');213    const values = await form.validateFields();214    expect(values.input1).toBe('789');215    expect(values.input2).toBe('456');216  });...helpers.js
Source:helpers.js  
1import { when } from 'jest-when'2let defaults = {3    pullRequestId: 1,4    repoId: '1',5    projectId: '1',6    targetBranch: 'refs/pull/1',7    sourceBranch: 'refs/pull/1',8    manualTarget: '',9    manualSource: '',10    msgValidacao: 'Validacao',11    prstatus: "3",12    autocomplete: "3"13}14let taskLibBuild = {15    getInput: jest.fn(),16    getVariable: jest.fn()17} 18when(taskLibBuild.getVariable).calledWith('Agent.JobName').mockReturnValue('Build');19when(taskLibBuild.getVariable).calledWith('Build.BuildUri').mockReturnValue('http://teste.com/build');20when(taskLibBuild.getVariable).calledWith('System.PullRequest.PullRequestId').mockReturnValue(defaults.pullRequestId);21when(taskLibBuild.getVariable).calledWith('System.TeamProjectId').mockReturnValue(defaults.projectId);22when(taskLibBuild.getVariable).calledWith('Build.Repository.ID').mockReturnValue(defaults.repoId);23when(taskLibBuild.getVariable).calledWith('System.PullRequest.TargetBranch').mockReturnValue(defaults.targetBranch);24when(taskLibBuild.getVariable).calledWith('System.PullRequest.SourceBranch').mockReturnValue(defaults.sourceBranch);25when(taskLibBuild.getInput).calledWith('msgvalidacao', true).mockReturnValue(defaults.msgValidacao);26when(taskLibBuild.getInput).calledWith('getDefaults').mockReturnValue('true');27when(taskLibBuild.getInput).calledWith('prstatus', true).mockReturnValue(defaults.prstatus);28when(taskLibBuild.getInput).calledWith('autocomplete', true).mockReturnValue(defaults.autocomplete);29let taskLibRelease = {30    getInput: jest.fn(),31    getVariable: jest.fn()32}33when(taskLibRelease.getVariable).calledWith('Agent.JobName').mockReturnValue('Release');34when(taskLibRelease.getVariable).calledWith('Release.ReleaseWebURL').mockReturnValue('http://teste.com/release');35when(taskLibRelease.getVariable).calledWith('Build.PullRequest.id').mockReturnValue(defaults.pullRequestId);36when(taskLibRelease.getVariable).calledWith('Build.projectId').mockReturnValue(defaults.projectId);37when(taskLibRelease.getVariable).calledWith('Build.Repository.id').mockReturnValue(defaults.repoId);38when(taskLibRelease.getVariable).calledWith('Build.PullRequest.TargetBranch').mockReturnValue(defaults.targetBranch);39when(taskLibRelease.getVariable).calledWith('Build.PullRequest.SourceBranch').mockReturnValue(defaults.sourceBranch);40when(taskLibRelease.getInput).calledWith('msgvalidacao', true).mockReturnValue(defaults.msgValidacao);41when(taskLibRelease.getInput).calledWith('getDefaults').mockReturnValue('true');42when(taskLibRelease.getInput).calledWith('prstatus', true).mockReturnValue(defaults.prstatus);43when(taskLibRelease.getInput).calledWith('prstatus', true).mockReturnValue(defaults.prstatus);44when(taskLibRelease.getInput).calledWith('autocomplete', true).mockReturnValue(defaults.autocomplete);45let taskLibManual =  {46    getInput: jest.fn(),47    getVariable: jest.fn()48}49when(taskLibManual.getVariable).calledWith('Agent.JobName').mockReturnValue('Release');50when(taskLibManual.getInput).calledWith('msgvalidacao').mockReturnValue(defaults.msgValidacao);51when(taskLibManual.getInput).calledWith('getDefaults').mockReturnValue('false');52when(taskLibManual.getInput).calledWith('targetbranch').mockReturnValue(defaults.manualTarget);53when(taskLibManual.getInput).calledWith('sourcebranch').mockReturnValue(defaults.manualSource);54when(taskLibManual.getInput).calledWith('repoId').mockReturnValue(defaults.projectId);55when(taskLibManual.getInput).calledWith('projectId').mockReturnValue(defaults.projectId);56when(taskLibManual.getInput).calledWith('prstatus', true).mockReturnValue(defaults.prstatus);57when(taskLibManual.getInput).calledWith('prstatus', true).mockReturnValue(defaults.prstatus);58when(taskLibManual.getInput).calledWith('autocomplete', true).mockReturnValue(defaults.autocomplete);59let taskLibManualWithUpdate =  {60    getInput: jest.fn(),61    getVariable: jest.fn()62}63when(taskLibManualWithUpdate.getVariable).calledWith('Agent.JobName').mockReturnValue('Release');64when(taskLibManualWithUpdate.getInput).calledWith('msgvalidacao').mockReturnValue(defaults.msgValidacao);65when(taskLibManualWithUpdate.getInput).calledWith('getDefaults').mockReturnValue('false');66when(taskLibManualWithUpdate.getInput).calledWith('targetbranch').mockReturnValue(defaults.manualTarget);67when(taskLibManualWithUpdate.getInput).calledWith('sourcebranch').mockReturnValue(defaults.manualSource);68when(taskLibManualWithUpdate.getInput).calledWith('repoId').mockReturnValue(defaults.projectId);69when(taskLibManualWithUpdate.getInput).calledWith('projectId').mockReturnValue(defaults.projectId);70when(taskLibManualWithUpdate.getInput).calledWith('prstatus', true).mockReturnValue(defaults.prstatus);71when(taskLibManualWithUpdate.getInput).calledWith('prstatus', true).mockReturnValue(defaults.prstatus);72when(taskLibManualWithUpdate.getInput).calledWith('autocomplete', true).mockReturnValue("2");73when(taskLibManualWithUpdate.getInput).calledWith('mergestrategy', true).mockReturnValue("2");74when(taskLibManualWithUpdate.getInput).calledWith('deletesourcebranch', true).mockReturnValue("true");75when(taskLibManualWithUpdate.getInput).calledWith('closeworkitens', true).mockReturnValue("true");...script.js
Source:script.js  
1// input_getting_function2function getInput(inputId) {3    const amount = document.getElementById(inputId).value;4    return amount;5}6//function for setting output in the required field7function setOutput(outputId, totalResult) {8    document.getElementById(outputId).innerText = totalResult;9}10//function for cleaing values for the saving part when clicking the calculate button11function clearingSavingPart() {12    setOutput('saving-amount', 0);13    setOutput('remaining-balance', 0);14    document.getElementById('save').value = '';15    document.getElementById('error2').style.display = 'none';16}17//function for updating the expenses & balance18function updateExpenses() {19    //input type error handling condition 20    if (getInput('food-expenses') >= 0 && getInput('rent-expenses') >= 0 && getInput('clothes-expenses') >= 0 && getInput('income') >= 0 && getInput('income') != '' && getInput('food-expenses') != '' && getInput('rent-expenses') != '' && getInput('clothes-expenses') != '') {21        const totalExpenses = parseFloat(getInput('food-expenses')) + parseFloat(getInput('rent-expenses')) + parseFloat(getInput('clothes-expenses'));22        setOutput('total-expenses', totalExpenses);23        //mathematical error handling condition24        if (getInput('income') > totalExpenses) {25            const balance = parseFloat(getInput('income')) - totalExpenses;26            setOutput('balance', balance);27            document.getElementById('error1').style.display = 'none';28            clearingSavingPart();29        }30        else if (getInput('income') < totalExpenses) {31            setOutput('balance', 0);32            setOutput('total-expenses', 0);33            document.getElementById('error1').style.display = 'block';34            clearingSavingPart();35        }36    }37    else {38        alert('Please Enter A Valid Amount')39    }40}41//function for updating the savings & remaining balance42function updateSavings() {43    //input type error handling condition 44    if (getInput('income') >= 0 && getInput('save') >= 0 && getInput('income') != '' && getInput('save') != '') {45        const savingAmount = parseFloat(getInput('income')) * parseFloat(getInput('save')) / 100;46        setOutput('saving-amount', savingAmount);47        //mathematical error handling condition48        if (document.getElementById('balance').innerText >= savingAmount) {49            const remainingBalance = document.getElementById('balance').innerText - savingAmount;50            setOutput('remaining-balance', remainingBalance);51            document.getElementById('error2').style.display = 'none';52        }53        else {54            setOutput('remaining-balance', 0);55            setOutput('saving-amount', 0);56            document.getElementById('error2').style.display = 'block';57        }58    }59    else {...index.js
Source:index.js  
...3async function run() {4  try {5    // Validate p12 keys.6    if (7      !core.getInput("p12-base64") &&8      (!core.getInput("p12-cer-base64") || !core.getInput("p12-key-base64"))9    ) {10      throw new Error("P12 keys missing or in the wrong format.");11    }12    // Validate mobileprovision13    if (!core.getInput("mobileprovision-base64")) {14      throw new Error("mobileprovision missing or in the wrong format.");15    }16    if (17      core.getInput("browserstack-upload").toLowerCase() === "true" &&18      (!core.getInput("browserstack-username") ||19        !core.getInput("browserstack-access-key"))20    ) {21      throw new Error("Browserstack username or access key missing.");22    }23    process.env.PROJECT_PATH = core.getInput("project-path");24    process.env.P12_BASE64 = core.getInput("p12-base64");25    process.env.P12_KEY_BASE64 = core.getInput("p12-key-base64");26    process.env.P12_CER_BASE64 = core.getInput("p12-cer-base64");27    process.env.MOBILEPROVISION_BASE64 = core.getInput(28      "mobileprovision-base64"29    );30    process.env.CODE_SIGNING_IDENTITY = core.getInput("code-signing-identity");31    process.env.TEAM_ID = core.getInput("team-id");32    process.env.WORKSPACE_PATH = core.getInput("workspace-path");33    process.env.EXPORT_METHOD = core.getInput("export-method");34    process.env.CONFIGURATION = core.getInput("configuration");35    process.env.CERTIFICATE_PASSWORD = core.getInput("certificate-password");36    process.env.OUTPUT_PATH = core.getInput("output-path");37    process.env.SCHEME = core.getInput("scheme");38    process.env.UPDATE_TARGETS = core.getInput("update-targets");39    process.env.DISABLE_TARGETS = core.getInput("disable-targets");40    process.env.BROWSERSTACK_UPLOAD = core.getInput("browserstack-upload");41    process.env.BROWSERSTACK_USERNAME = core.getInput("browserstack-username");42    process.env.BROWSERSTACK_ACCESS_KEY = core.getInput(43      "browserstack-access-key"44    );45    process.env.BUILD_PODS = core.getInput("build-pods");46    process.env.PODS_PATH = core.getInput("pods-path");47    await exec.exec(`bash ${__dirname}/../build.sh`);48  } catch (error) {49    core.setFailed(error.message);50  }51}...Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button');5    const articleHeader = await Selector('.result-content').find('h1');6    let headerText = await articleHeader.innerText;7});8module.exports = {9    getInput: async function (input) {10        return input;11    }12};13export default async function (input) {14    return input;15}Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button');5});6import { Selector } from 'testcafe';7test('My first test', async t => {8        .setFilesToUpload('#upload-file', [9        ]);10});Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3});4const nameInput = Selector('#developer-name');5const osOption = Selector('label').withText('Windows');6const submitButton = Selector('#submit-button');7test('My first test', async t => {8        .typeText(nameInput, 'Peter')9        .click(osOption)10        .click(submitButton);11});12import { Selector } from 'testcafe';13test('My first test', async t => {14});15const nameInput = Selector('#developer-name');16const osOption = Selector('label').withText('Windows');17const submitButton = Selector('#submit-button');18test('My first test', async t => {19        .typeText(nameInput, 'Peter')20        .click(osOption)21        .click(submitButton);22});23import { Selector } from 'testcafe';24test('My first test', async t => {25});26const nameInput = Selector('#developer-name');27const osOption = Selector('label').withText('Windows');28const submitButton = Selector('#submit-button');29test('My first test', async t => {30        .typeText(nameInput, 'Peter')31        .click(osOption)32        .click(submitButton);33});34import { Selector } from 'testcafe';35test('My first test', async t => {36});37const nameInput = Selector('#developer-nameUsing AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3});4async function getInput() {5    return Selector('input[type="text"]');6}7async function getButton() {8    return Selector('input[type="button"]');9}10test('My first test', async t => {11        .typeText(await getInput(), 'Peter')12        .click(await getButton());13});14test('My first test', async t => {15        .typeText(await getInput(), 'Peter')16        .click(await getButton());17});18test('My first test', async t => {19        .typeText(await getInput(), 'Peter')20        .click(await getButton());21});22test('My first test', async t => {23        .typeText(await getInput(), 'Peter')24        .click(await getButton());25});26test('My first test', async t => {27        .typeText(await getInput(), 'Peter')28        .click(await getButton());29});30test('My first test', async t => {31        .typeText(await getInput(), 'Peter')32        .click(await getButton());33});34test('My first test', async t => {35        .typeText(await getInput(), 'Peter')36        .click(await getButton());37});38test('My first test', async t => {39        .typeText(await getInput(), 'Peter')40        .click(await getButton());41});42test('My first test',Using AI Code Generation
1import {Selector} from 'testcafe';2const input = Selector('input');3test('My test', async t => {4        .typeText(input, 'Peter Parker')5        .click(Selector('#tried-test-cafe'));6});7import {Selector} from 'testcafe';8const input = Selector('input');9test('My test', async t => {10        .typeText(input, 'Peter Parker')11        .click(Selector('#tried-test-cafe'));12});13import {Selector} from 'testcafe';14const input = Selector('input');15test('My test', async t => {16        .typeText(input, 'Peter Parker')17        .click(Selector('#tried-test-cafe'));18});19import {Selector} from 'testcafe';20const input = Selector('input');21test('My test', async t => {22        .typeText(input, 'Peter Parker')23        .click(Selector('#tried-test-cafe'));24});25import {Selector} from 'testcafe';26const input = Selector('input');27test('My test', async t => {28        .typeText(input, 'Peter Parker')29        .click(Selector('#tried-test-cafe'));30});31import {Selector} from 'testcafe';32const input = Selector('input');33test('My test', async t => {34        .typeText(input, 'Peter Parker')35        .click(Selector('#tried-test-cafe'));Using AI Code Generation
1import { Selector, t } from 'testcafe';2test('My first test', async t => {3    const developerNameInput = Selector('#developer-name');4    const osOption = Selector('label').withText('macOS');5    const submitButton = Selector('#submit-button');6        .typeText(developerNameInput, 'Peter Parker')7        .click(osOption)8        .click(submitButton)9        .wait(5000);10});11import { Selector, t } from 'testcafe';12test('My first test', async t => {13    const developerNameInput = Selector('#developer-name');14    const osOption = Selector('label').withText('macOS');15    const submitButton = Selector('#submit-button');16        .typeText(developerNameInput, 'Peter Parker')17        .click(osOption)18        .click(submitButton)19        .wait(5000);20});21import { Selector, t } from 'testcafe';22test('My first test', async t => {23    const developerNameInput = Selector('#developer-name');24    const osOption = Selector('label').withText('macOS');25    const submitButton = Selector('#submit-button');26        .typeText(developerNameInput, 'Peter Parker')27        .click(osOption)28        .click(submitButton)29        .wait(5000);30});31import { Selector, t } from 'testcafe';32test('My first test', async t => {33    const developerNameInput = Selector('#developer-name');34    const osOption = Selector('label').withText('macOS');Using AI Code Generation
1import { Selector, t } from 'testcafe';2const testControllerHolder = require('../testControllerHolder.js');3const getInput = require('../getInput.js');4test('My first test', async t => {5        .typeText(Selector('#lst-ib'), 'Hello, World!')6        .click(Selector('.lsb'));7    await t.click(Selector('h3').withExactText('Hello, World!'));8    const testController = testControllerHolder.get();9    const input = await getInput(testController, 'Hello, World!');10    await t.expect(input).eql('Hello, World!');11});12const testControllerHolder = require('../testControllerHolder.js');13module.exports = async function getInput(testController, selector) {14    testControllerHolder.hold(testController);15    return await testController.eval(() => {16        const testControllerHolder = require('../testControllerHolder.js');17        const testController = testControllerHolder.free();18        return testController.selectTextAreaContent(Selector('#lst-ib'));19    }, { dependencies: { testControllerHolder } });20};21let testController = null;22exports.hold = tc => {23    testController = tc;24};25exports.get = () => {26    return testController;27};28exports.free = () => {29    const tc = testController;30    testController = null;31    return tc;32};Using AI Code Generation
1fixture('Getting Started')2test('My first test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#submit-button');5    await t.expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7const { Selector } = require('testcafe');8const getInput = Selector('#developer-name');9fixture('Getting Started')10test('My first test', async t => {11        .typeText(getInput, 'John Smith')12        .click('#submit-button');13    await t.expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');14});15const { Selector } = require('testcafe');16const getInput = Selector('#developer-name');17fixture('Getting Started')18test('My first test', async t => {19        .typeText(getInput, 'John Smith')20        .click('#submit-button');21    await t.expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');22});23const { Selector } = require('testcafe');24const getInput = Selector('#developer-name');25fixture('Getting Started')26test('My first test', async t => {27        .typeText(getInput, 'John Smith')28        .click('#submit-button');29    await t.expect(Selector('#article-header').innerText).eqlLearn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
