How to use matchLocation method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

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

solution.js

Source: solution.js Github

copy
1function solve() {
2    let code = document.getElementById('string').value;
3    //let code = '4ds';
4    let input = document.getElementById('text').value;
5    //let input = 'eaSt 19,432567noRt north east 53,123456north 43,3213454dsNot all those who wander are lost.4dsnorth 47,874532';
6    let result = document.getElementById('result');
7
8    let patternMessage = new RegExp(`${code}(.*)${code}`, 'g');
9    let message = patternMessage.exec(input)[1];
10
11    let east = '';
12    let north = '';
13    let location = /(north|east).*?(\d{2})[^,]*?,[^,]*?(\d{6})/gmi;
14    let matchLocation = location.exec(input);
15    while (matchLocation !== null) {
16        if (matchLocation[1].toLocaleUpperCase() === 'NORTH') {
17            north = matchLocation;
18        } else {
19            east = matchLocation;
20        }
21        matchLocation = location.exec(input);
22    }
23
24    let p1 = document.createElement('p');
25    p1.textContent = `${north[2]}.${north[3]} N`;
26
27    let p2 = document.createElement('p');
28    p2.textContent = `${east[2]}.${east[3]} E`;
29
30    let p3 = document.createElement('p');
31    p3.textContent = `Message: ${message}`;
32
33    result.appendChild(p1);
34    result.appendChild(p2);
35    result.appendChild(p3);
36}
Full Screen

ProductSkuInCartClassifier(1).js

Source: ProductSkuInCartClassifier(1).js Github

copy
1define('classification/ProductSkuInCartClassifier',
2	   ['classification/KeywordClassifier', 'util/TextUtil', 'util/Distance'],
3	   function(KeywordClassifier, TextUtil, DistanceUtil){
4	//matches an element from the scan to a single attribute
5
6	const RelaxLevel = { STRICT:0, RELAXED:1, LOOSE:2};
7
8	class ProductSkuInCartClassifier extends KeywordClassifier {
9
10		constructor(definition, product){
11			super(definition);
12
13			if(typeof product === 'string') {
14				this.product = JSON.parse(product);
15			} else {
16				this.product = product;
17			}
18			
19			this.attributeExceptions = ['one size', '1 size', 'one color', '1 color'];
20			this.nameMatches = [];
21			this.attributeMatches = {};
22						
23			//Average Distance to Geometric Median of classified text
24			this.proximity = 100;
25
26			//Relaxation Level
27			this.relaxation = RelaxLevel.STRICT;
28
29			this.initializeAttributes(this.product);
30			this.resetAttrMatches();
31		}
32
33		getProductName() {
34			let name = '';
35			try
36			{
37				name = (new DOMParser).parseFromString(this.product.name, 'text/html').body.innerText;
38			} catch(err) {
39				name = this.product.name;
40			}
41			return TextUtil.cleanText(name);
42		}
43
44		hasAttributes() {
45			return Array.isArray(this.attributeKeys) && this.attributeKeys.length > 0;
46		}
47
48		reset() {
49			super.reset();
50			this.nameMatches = [];
51			this.resetAttrMatches();
52		}
53
54		resetAttrMatches() {
55			if(!this.hasAttributes()) return;
56
57			this.attributeKeys.forEach(function(att) {
58				this.attributeMatches[att] = [];
59			}, this);
60		}
61
62		initializeAttributes(product) {
63			let allKeys = Object.keys(product.attributes);
64
65			this.attributeKeys = [];
66			this.attributes = {};
67
68			allKeys.forEach(function(attrKey){
69				let attr = product.attributes[attrKey], attrLabel;
70
71				attrLabel = TextUtil.cleanText(attr.label);
72				if(this.attributeExceptions.indexOf(attrLabel) === -1) {
73					this.attributes[attrKey] = Object.assign({}, attr);
74					this.attributeKeys.push(attrKey);
75				}
76
77			}, this);
78		}
79
80		matchesKeywords(element, scannedTextList){
81			
82			let humanText = this.getVisibleText(element),
83				matchFound = false,
84				matchLocation='',
85				matchType='',
86				nameMatchTest=false,
87				titleMatch = false,
88				keywordMatch = false;
89
90			nameMatchTest = this.matchesName(element, humanText);
91
92			if(nameMatchTest) {
93				this.nameMatches.push({element:element, matchLocation:KeywordClassifier.Matching.MatchLocation.HUMAN, matchType:KeywordClassifier.Matching.MatchType.EXACT});
94				return true;
95			}
96
97			if(TextUtil.containsMatch(humanText, [this.getProductName()])) {
98				this.nameMatches.push({element:element, matchLocation:KeywordClassifier.Matching.MatchLocation.HUMAN, matchType:KeywordClassifier.Matching.MatchType.CONTAINS});
99
100				if(this.hasAttributes()) {
101					this.matchAttributes(element, humanText);
102				}
103
104				return true;
105			}
106			else if(this.hasAttributes()) {
107				return this.matchAttributes(element, humanText);
108			}
109
110
111
112
113
114			/*
115			if(productHasIcon && element.imageSource && element.imageSource.length > 0) {
116
117				var containsSrcMatch = TextUtil.containsMatch([element.imageSource],[this.getIcon()]);
118
119				if(containsSrcMatch){
120					this.keywordMatches.push({element:element, matchLocation:KeywordClassifier.Matching.MatchLocation.IMAGE, matchType:KeywordClassifier.Matching.MatchType.EXACT});
121					return true;
122				}
123
124			} else {
125				//Look inside the options to see if there is an option that matches the one we want to select
126				if(element.tagName === 'SELECT') {
127					if(this.matchElementOptions(element)) {
128						this.keywordMatches.push({element:element, matchLocation:KeywordClassifier.Matching.MatchLocation.HUMAN, matchType:KeywordClassifier.Matching.MatchType.EXACT});
129						return true;
130					}					
131				}
132
133				if(this.attributeTitle.length > 0) {
134					if(TextUtil.exactMatch(humanText, [this.attributeTitle, this.attributeTitle.toLowerCase()])) {
135						matchFound = true;
136						matchLocation = KeywordClassifier.Matching.MatchLocation.HUMAN;
137						matchType = KeywordClassifier.Matching.MatchType.EXACT;
138						negativeMatch = this.negativeWordMatch(humanText);
139					} else if(TextUtil.containsMatch(humanText, [this.attributeTitle])) {
140						matchFound = true;
141						matchLocation = KeywordClassifier.Matching.MatchLocation.HUMAN;
142						matchType = KeywordClassifier.Matching.MatchType.CONTAINS;
143						negativeMatch = this.negativeWordMatch(humanText);
144					}
145
146					if(negativeMatch) { matchFound = false; }
147
148					if(matchFound) {
149						this.titleMatches.push({element:element, matchLocation:matchLocation, matchType:matchType});
150						titleMatch = true;
151					}
152				}
153
154				keywordMatch = super.matchesKeywords(element, scannedTextList);
155
156				return (titleMatch || keywordMatch);
157			}
158
159			*/
160		 	
161		}
162
163		matchesName(element, elementText) {
164			let replaceRegex = /[^\s\w]+/g, productText = this.getProductName().replace(replaceRegex,'');
165
166			switch(this.relaxation) {
167				
168				case RelaxLevel.RELAXED:
169					elementText = elementText.map(function(t) {
170						return t.replace(replaceRegex,'');
171					});
172					return TextUtil.exactMatch(elementText, [productText]);
173				break;
174				case RelaxLevel.LOOSE:
175					elementText = elementText.map(function(t) {
176						return t.replace(replaceRegex,'');
177					});
178					let productParts = productText.split(' ').filter(function(text) { return text !== '';}), exactOrderScore=0, matchingWordScore=0;
179
180					exactOrderScore = TextUtil.exactOrderScore(elementText, productParts);
181					
182					matchingWordScore = TextUtil.wordMatchScore(elementText, productParts);
183
184					return exactOrderScore > .5 || matchingWordScore > .5;
185
186				break;
187				case RelaxLevel.STRICT:
188					return TextUtil.exactMatch(elementText, [this.getProductName()]);
189				break;
190				default: 
191					return false;
192					break;
193				
194			}
195			
196		}
197
198		matchAttributes(element, extractedElementText) {
199			if(!this.hasAttributes()) return false;
200
201			let attr, attrMatch = false, nodeValue;
202
203
204			this.attributeKeys.forEach(function(key){
205				attr = this.attributes[key];
206
207				if(TextUtil.exactMatch(extractedElementText, [TextUtil.cleanText(attr.label)])) {
208					this.attributeMatches[key].push({element:element, matchLocation:KeywordClassifier.Matching.MatchLocation.HUMAN, matchType:KeywordClassifier.Matching.MatchType.EXACT});
209					attrMatch = true;
210				} else if(TextUtil.containsMatch(extractedElementText, [TextUtil.cleanText(attr.label)])) {
211					this.attributeMatches[key].push({element:element, matchLocation:KeywordClassifier.Matching.MatchLocation.HUMAN, matchType:KeywordClassifier.Matching.MatchType.CONTAINS});
212					attrMatch = true;
213				} else {
214					//Look at just node value and see if a portion of it matches the attribute
215					nodeValue = element.nodeValue;
216					if(nodeValue) {
217						if(TextUtil.containsMatch([TextUtil.cleanText(attr.label)], [nodeValue])) {
218							//Calculate the percentage match by using word count
219							var labelCount = attr.label.split(' ').length;
220							var nodeValueCount = nodeValue.split(' ').length;
221							if(labelCount > 0 && ((nodeValueCount/labelCount) > .32)) {
222								this.attributeMatches[key].push({element:element, matchLocation:KeywordClassifier.Matching.MatchLocation.HUMAN, matchType:KeywordClassifier.Matching.MatchType.CONTAINS});
223							}
224						}
225					}
226				}
227			}, this);
228
229			return attrMatch;
230		}
231
232		getVisibleText(element) {
233			let textArray = [];
234			if(element.buttontext) {
235				this.sanitize(element.buttontext, textArray);
236			}
237			if(element.nodeValue) {
238				this.sanitize(element.nodeValue, textArray);
239			}
240			if(element.innerText){
241				this.sanitize(element.innerText, textArray);
242			}
243				
244			if(element.ariaLabel){
245				this.sanitize(element.ariaLabel,textArray);
246			}	
247
248			if(element.dataTitle){
249				this.sanitize(element.dataTitle,textArray);
250			}	
251
252			if(element.value){
253				this.sanitize(element.value, textArray);
254			}
255
256			if(element.title){
257				this.sanitize(element.title, textArray);
258			}
259			return textArray;
260		}
261
262		postMatchUpdate() {
263			let nameFound = false, attrsFound = true, elementClusters, attrMatchCount=0;
264
265			if(this.nameMatches.length > 0) {
266				nameFound = true;
267			}
268
269			if(this.hasAttributes()) {
270
271				attrMatchCount = this.attributeKeys.filter(function(attrKey) {
272					return this.attributeMatches[attrKey].length > 0;
273				}, this).length;
274
275				if(this.relaxation === RelaxLevel.STRICT) {
276					//All must match
277					attrsFound = attrMatchCount === this.attributeKeys.length;					
278				} else {
279					
280					attrsFound = (attrMatchCount / this.attributeKeys.length) >= .5;
281				}
282				
283			}
284
285			if( nameFound && attrsFound) {
286
287				elementClusters = this.findNearestClusters();
288
289				elementClusters = elementClusters.filter(function(c){
290					return c.distanceSummary.mean <= this.proximity;
291				}, this);
292
293				elementClusters.sort(function(c1, c2) {
294					let c1Mean = c1.distanceSummary.mean, c2Mean = c2.distanceSummary.mean;
295
296					if(c1Mean < c2Mean) {
297						return -1;
298					}
299					else if(c1Mean > c2Mean) {
300						return 1;
301					}
302					else {
303						return 0;
304					}
305				});
306
307				if(elementClusters.length > 0) {
308					this.matchingElement = elementClusters[0].referenceElement;
309				}
310			}
311		}
312
313
314		findNearestClusters() {
315			let clusters = [], attrLists = [];
316
317			
318			this.attributeKeys.forEach(function(attrKey) {
319				if(this.attributeMatches[attrKey].length > 0) {
320					attrLists.push([]);
321					this.attributeMatches[attrKey].forEach(function(attrMatch) {
322						this[this.length-1].push(attrMatch.element);
323					}, attrLists);	
324				}
325				
326			}, this);
327
328			this.nameMatches.forEach(function(match) {
329				var elements = DistanceUtil.findNearestClusterTo(match.element, attrLists, 0, 0, []);
330				var gMedian = DistanceUtil.findGeometricMedian(elements);
331				var distanceSummary = DistanceUtil.getDistanceSummary(gMedian, elements);
332				var  clusterData = {referenceElement:match.element, elements:elements, distanceSummary: distanceSummary};
333				clusters.push(clusterData);
334			}, this);
335
336			return clusters;
337		}
338
339		relax() {
340
341			if(this.relaxation < RelaxLevel.LOOSE) {
342				this.relaxation += 1;
343			}
344		}
345
346
347
348
349
350	}	
351
352	return ProductSkuInCartClassifier;
353
354});
355
356
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)