Cypress IO- Writing a For Loop - javascript

I have 15 buttons on a page. I need to test each button.
I tried a simple for loop, like
for (var i = 1; i < 15; i++) {
cy.get("[=buttonid=" + i + "]").click()
}
But Cypress didn't like this. How would I write for loops in Cypress?

To force an arbitrary loop, I create an array with the indices I want, and then call cy.wrap
var genArr = Array.from({length:15},(v,k)=>k+1)
cy.wrap(genArr).each((index) => {
cy.get("#button-" + index).click()
})

Lodash is bundled with Cypress and methods are used with Cypress._ prefix.
For this instance, you'll be using the _.times. So your code will look something like this:
Cypress._.times(15, (k) => {
cy.get("[=buttonid=" + k + "]").click()
})

You can achieve something similar to a "for loop" by using recursion.
I just posted a solution here: How to use a while loop in cypress? The control of is NOT entering the loop when running this spec file? The way I am polling the task is correct?
Add this to your custom commands:
Cypress.Commands.add('recursionLoop', {times: 'optional'}, function (fn, times) {
if (typeof times === 'undefined') {
times = 0;
}
cy.then(() => {
const result = fn(++times);
if (result !== false) {
cy.recursionLoop(fn, times);
}
});
});
Then you can use it by creating a function that returns false when you want to stop iterating.
cy.recursionLoop(times => {
cy.wait(1000);
console.log(`Iteration: ${times}`);
console.log('Here goes your code.');
return times < 5;
});

While cy.wrap().each() will work (one of the answers given for this question), I wanted to give an alternate way that worked for me. cy.wrap().each() will work, but regular while/for loops will not work with cypress because of the async nature of cypress. Cypress doesn't wait for everything to complete in the loop before starting the loop again. You can however do recursive functions instead and that waits for everything to complete before it hits the method/function again.
Here is a simple example to explain this. You could check to see if a button is visible, if it is visible you click it, then check again to see if it is still visible, and if it is visible you click it again, but if it isn't visible it won't click it. This will repeat, the button will continue to be clicked until the button is no longer visible. Basically the method/function is called over and over until the conditional is no longer met, which accomplishes the same thing as a for/while loop, but actually works with cypress.
clickVisibleButton = () => {
cy.get( 'body' ).then( $mainContainer => {
const isVisible = $mainContainer.find( '#idOfElement' ).is( ':visible' );
if ( isVisible ) {
cy.get( '#idOfElement' ).click();
this.clickVisibleButton();
}
} );
}
Then obviously call the this.clickVisibleButton() in your test. I'm using typescript and this method is setup in a class, but you could do this as a regular function as well.

// waits 2 seconds for each attempt
refreshQuote(attempts) {
let arry = []
for (let i = 0; i < attempts; i++) { arry.push(i) }
cy.wrap(arry).each(() => {
cy.get('.quote-wrapper').then(function($quoteBlock) {
if($quoteBlock.text().includes('Here is your quote')) {
}
else {
cy.get('#refreshQuoteButton').click()
cy.wait(2000)
}
})
})
}

Try template literals using backticks:
for(let i = 0; i < 3; i++){
cy.get(`ul li:nth-child(`${i}`)).click();
}

Related

How to optimize native JavaScript code when refactoring it from Jquery

I need to rewrite some Jquery into native JavaScript code but I am facing a problem that I am not so sure how to solve.
This is Jquery code I need to rewrite in native JS:
$('.class1').click(function () {
setTimeout(() => {
$('.class2').css('top', '252px');
$('.class3').css('bottom', '0px');
}, 200);
$('.class2').css('z-index', '-1');
$('.class1').css('z-index', '-1');
});
And this is what I have written in native JavaScrip:
if (document.querySelector('.class1')){
document.querySelector('.class1').addEventListener('click', function () {
setTimeout(() => {
if (document.querySelector('.class2')) {
document.querySelector('.class2').style.top = '252px';
}
if ( document.querySelector('.class3')) {
document.querySelector('.class3').style.bottom = '0px';
}
}, 200);
if (document.querySelector('.class2')) {
document.querySelector('.class2').style.zIndex = '-1';
}
if ( document.querySelector('.class1')) {
document.querySelector('.class1').style.zIndex = '-1';
}
})
}
I was hoping that people could explain to me how to solve two things:
Is there a more elegant way to check for an element on the current page if the code runs on the whole site?
Is there something else that I can replace those if statements inside the function?
In Jquery those statements are executed one by one but in my case I need to check for an element first and if it is there do something with it.
You can make the code more succinct by storing the result of querySelector within a variable. Also note that a class selector in jQuery can return multiple elements, so the native equivalent of it is querySelectorAll().
As such you will need to loop through all the elements in that collection and add the event handlers, or update their style, as necessary. Due to this loop you don't need to explicitly check for the existence of the elements, as the forEach() will simply not execute if the collection is empty.
With that said, try this:
let class1 = document.querySelectorAll('.class1');
let class2 = document.querySelectorAll('.class2');
let class3 = document.querySelectorAll('.class3');
class1.forEach(el => {
el.addEventListener('click', e => {
setTimeout(() => {
class2.forEach(el => el.style.top = '252px');
class3.forEach(el => el.style.top = '0px');
}, 200);
class1.forEach(el => el.style.zIndex = -1);
class2.forEach(el => el.style.zIndex = -1);
});
});

Protractor nested for loops

I need some help with a nested for loop in protractor and converting/understanding promises correctly. In ‘test’ below the functionality works with all values, but as soon as I try to put in the nested for loops things go south. Any chance someone has a clean suggestion on this? I have tried the forEach which some indicate handle the promise issue inherently, but I seem to get the same results.
My Test data looks like:
objectPage.chartValues = {
[['chart','ChartID01'],['title','TitleText01'],['Name01','value01'],['Name02','Value02']],
[[‘chart','ChartID02'],['title','TitleText02'],['Name01','value01'],['Name02','Value02']],
[[‘chart','ChartID03'],['title','TitleText03'],['Name01','value01'], [‘Name02’,'Value02'],['Name03','Value03']]
}
it ('test', function (){
for (chartNumber = 0; chartNumber < objectPage.chartValues.length; chartNumber++) {
for (chartEntry = 1; chartEntry < ObjectPage.chartValues[chartNumber].length; chartEntry++) {
//for readability of next call pulled out here
chart = objectPage.chartValues[chartNumber][0][1];
name = objectPage.chartValues[chartNumber][chartEntry][0];
value = objectPage.chartValues[chartNumber][chartEntry][1];
pageObject.getbackgroundcolor(chart, name).then(function (color) {
expect(pageObject.getElementFromTable(chart, name, color).getText())
.toEqual(value);
});
}
}
});
//function calls in pageobject the call for get background is straight forward.
this.getbackgroundcolor = function (chartName, valueName) {
return element(by.id(chartName)).element(by.cssContainingText('.dxc-item', valueName)).element(by.tagName('rect')).getAttribute('fill');
//get element is very similar.
this.getElementFromTable = function(chartName, valueName, colorname) {
some searching stuff..
return element(by.css(‘tspan'));
My results seem to indicate the look executes, but not returning from the actual expect. Finally trying to find a value for an item with background color of null. I know this is not true as I have run all values individually and in sequence without issue. Hopefully I avoided cut and past/generalization errors.
Thank you.
Update:
it('Verify Charts on page ', function () {
myChartlength = objectPage.chartValues.length;
for (chartNumber = 0; chartNumber < myChartlength; chartNumber++) {
(function (chartNumber) {
myEntrylength = objectPage.chartValues[chartNumber].length;
chartValues = objectPage.chartValues[chartNumber];
for (chartEntry = 2; chartEntry < myEntrylength; chartEntry++) {
(function (chartEntry) {
//pulled these out for readablility of next call.
chart = chartValues[0][1];
name = chartValues[chartEntry][0];
value = chartValues[chartEntry][1];
console.log('chart: ' + chart + ', name: ' + name + ', value: ' + value);
page.getbackgroundcolor(chart, name).then(function (color) {
expect(objectPage.getElementFromTable(chart, name, color).getText()).toEqual(value);
});
})(chartEntry);
};
})(chartNumber);
};
});
Yeah, if I'm understanding your question correctly, your problem is async. It's firing through the loops before any promises are returned.
To loop tests, the best solution I've found is to use an IIFE (Instantly Invoked Function Expression). In which, you create your loop, create the iife, and pass in the index.
Here's a basic example:
describe('to loop tests', function() {
var data = ['1', '2', '3'];
for(var i = 0; i < data.length; i++) {
// create your iife
(function(i) {
it('pass in the index to an iife', function() {
console.log('i is: ' + i);
expect(data[i]).toBe(true);
});
})(i); // pass in index
}
});
This works great for data driving tests from say a data file, or whatever. And if you need multiple loops, like in your example code, you'll just make multiple iifes.
You shouldn't use for loops with protractor or you will have a bad time.
Due to the asynchronous nature of Protractor, if you need loops, I see async's map https://github.com/caolan/async as one good and clean solution.
Other option is to use ES5's map when you need loops in Protractor, such as:
[1,3,5,7].map(function(index,key){
expect(element.all(by.css('.pages-list')).get(index).isDisplayed()).toBeFalsy()
})
In your case, I see that you need a for loops to produce array, that you later can map over it.
You can have this array with function, that uses for loops inside and returns the needed array to a callback.
Simple example with one for loop
function returnIndexes(callback){
var exitArray = [];
for (var i = 0; i < someArray.length; i++) {
if(someArray[i].length > 12){
exitArray.push(someArray[i]);
}
if(i==someArray.length-1){
callback(exitArray);
}
}

Array value as condition of if else- JS

I've been trying to understand why whenever value of the array I click, it always add the class "foo".
Example: I clicked on London (cities[1], right?) and it added the class foo.
var cities = [
document.getElementById('Paris'),
document.getElementById('London'),
document.getElementById('Berlin')
];
for (var i = 0; i < cities.length; i++) {
cities[i].onclick = test;
function test(){
if(cities[i] === cities[0]) {
el.classList.add("foo");
}
}
}
EDIT: my original answer was incorrect, this updated one is right. addEventListener returns nothing. Instead, you should use some kind of wrapper to add and remove your listeners, again so that you don't waste resources on listeners that you aren't using:
function on (element, eventName, callback) {
element.addEventListener(eventName, callback);
return function unregister () {
element.removeEventListener(callback);
}
}
function test (event) {
if (event.currentTarget===cities[0]) {
event.target.classList.add('foo');
}
}
var listenerRemovers = cities.map(function (city) {
return on(city, 'click', test);
});
Now you can remove any of these listeners by calling the corresponding function in your listenerRemovers array:
listenerRemovers.forEach(function (unRegisterFunc) { unRegisterFunc(); });
ORIGINAL WRONG ANSWER:
For what it's worth, you're probably better off using .map in a case like this, since best practice is to keep a reference to the event listeners so you can cancel them if needed.
function test (event) {
if (event.currentTarget===cities[0]) {
event.target.classList.add('foo');
}
}
var listenerHandlers = cities.map(function (city) {
return city.addEventListener('click', test);
});
This is happening because you are setting the event functions inside a loop. Each function is using the same value of i.
Try to use this instead of trying to cities[i] inside the function.
function test(){
if(this === cities[0]) {
el.classList.add("foo");
}
}
The easiest approach to achieve this functionality is to use jQuery, here is the idea:
In html tags, give those cities a common class, e.g. class="city"
$('.city').click(function(){$('.city').addClass('foo')});
jQuery saves you more time and coding efforts.
The problem is you are trying to assign a function to a DOM attribute. You are not registering a listener but modifying the DOM. If you wish to do it this way, you must assign the onclick as cities[i].onclick = 'test()'
Also, you should move the function test outside of the for loop to look like the following. The problem is the function test is being declared many times, each with a different 'i' value.
for (var i = 0; i < cities.length; i++) {
cities[i].onclick = 'test(this)';
}
function test(el){
if(cities[i] === cities[0]) {
el.classList.add("foo");
}
}

How do I clean up this jQuery function?

I have this function that I would like to condense into some iterator. How could this function be cleaned up?
All need to act sequentially, as in: When one function returns, the next one begins. All odd children should fade out after fading in, and all even children should fade in and not fade out after.
Please note that this code is in CoffeeScript, so no semicolons.
I'm also having a problem with after the 8th child (e.g. if I continue on to '.title-sword:nth-child(9), etc) the function stops working. My thinking is there is a limit for embedded functions in depth but I am not able to verify this.
$('.title-sword:nth-child(2)').css('visibility', 'visible').hide().fadeIn('fast').fadeOut('fast', ->
$('.title-sword:nth-child(3)').css('visibility', 'visible').hide().fadeIn('fast', ->
$('.title-sword:nth-child(4)').css('visibility', 'visible').hide().fadeIn('fast').fadeOut('fast', ->
$('.title-sword:nth-child(5)').css('visibility', 'visible').hide().fadeIn('fast', ->
$('.title-sword:nth-child(6)').css('visibility', 'visible').hide().fadeIn('fast').fadeOut('fast', ->
$('.title-sword:nth-child(7)').css('visibility', 'visible').hide().fadeIn('fast', ->
$('.title-sword:nth-child(8)').css('visibility', 'visible').hide().fadeIn('fast').fadeOut('fast')
)
)
)
)
)
)
Try something like this (no CoffeeScript, since I'm just a regular JS guy):
(function() {
var i=2, elm,
step = function() {
elm = $('.title-sword:nth-child('+i+')');
if( !elm) return;
elm.css('visibility','visible').hide();
if( i%2 == 0) elm.fadeIn('fast').fadeOut('fast',step);
else elm.fadeIn('fast',step);
i++;
};
step();
})();
This code will run the desired function starting with the second child, and repeating until there are no more children.
try this:
$('.title-sword:nth-child(n+2):not(:nth-child(n+9))').css('visibility', 'visible').hide().fadeIn('fast').fadeOut('fast')
http://jsfiddle.net/RfHj2/1/
Assuming the elements are all siblings, this should work:
function doFades($el){
$el.css('visibility', 'visible').hide().fadeIn('fast').fadeOut('fast', function(){
var $next=$(this).next();
if($next.length){
doFades( $next);
}
});
}
doFades( $('.title-sword:nth-child(2)') );
I'm not familiar with coffeescript syntax but should be easy to modify
I prefer to run the selector operation just once and then iterate through the results of that. Here's a generic function that could be used for your purpose:
fadeInOutChildren(parentSelector, lowChild, highChild) {
var items = $(parentSelector).children();
var index = lowChild;
function next() {
if (index <= highChild) {
items.eq(index++).css('visibility', 'visible').hide().fadeIn('fast').fadeOut('fast', next);
}
}
next();
}
fadeInOutChildren(".title-sword", 1, 7);

JSHint error Don't make functions within a loop

I'm running some code through JSHint and I keep getting the following error:
Don't make functions within a loop.
I tried turning off the warning for 'About functions inside loops' off which does nothing to stop the error from being reported. I have decided to refactor the code, using JSHint's suggestions here, http://www.jshint.com/options/ but I'm still getting the error. I was hoping that somebody could help me to refactor this code slightly so it will pass. Here's a copy of the function:
function setSounds(parent) {
var i,
l;
parent.getElements('.sound').each(function (elem) {
var soundEvents = [];
if (elem.get('fk_click_sound')) {
soundEvents.push('click');
}
if (elem.get('fk_mouseover_sound')) {
soundEvents.push('mouseenter');
}
if (soundEvents.length !== 0) {
for (i = 0, l = soundEvents.length; i < l; i += 1) {
elem.addEvent(soundEvents[i], (function () {
return function (e) {
FKSoundAIR(FKSoundStd[this.get('fk_' + e.type + '_sound')]);
};
})(elem), false);
}
}
});
}
I'm using MooTools. The purpose of this function is to pass a parent element and then apply sound event to all of the children with the class 'sound.' I'm using custom HTML attributes, such as 'fk_click_sound' to feed additional information to the function. I picked up this method of assigning a function within a loop from http://blog.jbrantly.com/2010/04/creating-javascript-function-inside.html.
Any suggestions or resources that you can point me to would be great. Thanks!
You can try something like this:
function make_handler(div_id) {
return function () {
alert(div_id);
}
}
for (i ...) {
div_id = divs[i].id;
divs[i].onclick = make_handler(div_id);
}
You could create the function outside, assign it to a var and use it in your call to addEvent.
As it turns out JS Hint had a bug re: the warning for Looping inside of a function, which they fixed here. Now that this is fixed, this issue is resolved.

Categories

Resources