how to click on an element until it is appearing (Cypress) - javascript

I need to click on pop-ups until they appearing. But there is the issue because on the different tabs in the application I have to click in them different number of times.
In python i just used loop with if and else, whenever some particular locator appeared I clicked in it, and when it is not present anymore I used else pass.
There is any solution in Cypress how can I click in a pop-up 4,5 or 6 times with if/else and continue test suite performing when a pop-up is not present anymore?
Maybe something with if-return, else-expect?
Cypress.Commands.add("acceptPopup", () => {
for (let n = 0; n < 20; n++) {
if (cy.xpath('//button[contains(#title,"Last")]', {
timeout: 100000
}).should("be.visible")) {
return cy.xpath('//button[contains(#title,"Last")]').click();
}
}
});
Thanks!

Related

Bookmarklet to run different functions depending on times clicked

Is it possible to design a bookmarklet to run different scenarios based on the number of times it was clicked?
I tried to do this via addEventListener when clicked and setTimeout(main, 5000), then counting the eventListeners' fires when main() finally runs. It works after a fashion, but there are two problems with this approach:
Clicks are caught and counted if the bookmarklet is invoked as a link on a webpage, but not, of course, if clicked on Bookmark Bar. This is unresolvable, I believe; the number of clicks has to be evaluated when the last main function runs somehow…
Say, I clicked the bookmarklet 3 times; main() runs 3 times spaced 5000ms apart. How do I make it run only the once? And only the last one at that, to resolve the problem in #1? The way I do it is so cumbersome as to be all but useless, and is prone to racing besides.
The main question though is that I feel my approach, even if viable, is far too clumsy. I'm aware I can use, say, prompt() and have the user enter the number of a scenario, or render a menu and click a required scenario, but is there a way to do that based simply on the number of clicks / snippet runs within a given time frame?
Check if this is what you need:
javascript: (() => {
window.bmClicked = window.bmClicked ? window.bmClicked + 1 : 1;
clearTimeout(window.bmTimeout);
window.bmTimeout = setTimeout(() => {
console.log('window.bmClicked: ', window.bmClicked);
window.bmClicked === 1 && functionOne();
window.bmClicked === 2 && functionTwo();
window.bmClicked === 3 && functionThree();
window.bmClicked = null;
}, 500);
function functionOne() {
console.log('functionOne');
}
function functionTwo() {
console.log('functionTwo');
}
function functionThree() {
console.log('functionThree');
}
})();

I have a list of request numbers(strings) displayed in table format in my app and it has pagination, so have multiple page table of contents

i have a for loop to iterate the pages and used each block to iterate request numbers within the table in that page. When request no in the table matches my request it should select that and exit the loop. I am stuck here as I cannot break the loop .
M_SelectRequestNoThen(request) {
let exit = true;
let i;
cy.wait(500);
this.E_TotalPages()
.invoke("text")
.then((text) => {
let total = text;
cy.log("totalpages", total);
for (i = 0; i < total; i++) {
cy.log("i inside while", i);
this.E_RequestRows().each(($el, $index) => {
cy.wrap($el)
.invoke("text")
.then((text) => {
cy.log("text", text);
if (text.trim().includes(request)) {
this.E_RequestSelect(request).click();
exit = false;
}
});
});
i++;
if (exit) {
this.E_NextButton().click();
} else {
break;
}
}
});
}
as i cannot use break in then block;used boolean exit but even that doesnt get updated value outside then block. so even if my request is found it navigates to next page. so how can i break my for loop after 'if (text.trim().includes(request))' condition is satisfied?
You have some issues of control flow here, primarily that you are trying to break inside an asynchronous Promise. However, I don't think you need that complexity and can leverage the test framework better doing something more simple like this instead (might be a little off because I'm not sure exactly what you're testing here):
this.E_RequestRows().each(($el, $index) => {
if ($el.contains(request)) {
this.E_RequestSelect(request).click();
break; // assuming you want to stop this iteration when you find your element
}
});
My scenario is I have 4 pages of lists. if my string is not found in first page it has to click on next page. In that fashion it has to iterate list and pages both until string is found and then exit. If its single page scenario my each block works. if string is not found in that entire first page i have to check outside each block either to go for next page or break the loop.

Run several small test within one 'it' in E2E test using Protractor

I am working on a E2E test for a single-page web application in Angular2.
There are lots of clickable tags (not redirected to other pages but has some css effect when clicking) on the page, with some logic between them. What I am trying to do is,
randomly click a tag,
check to see the the response from the page is correct or not (need to grab many components from the web to do this),
then unclick it.
I set two const as totalRound and ITER, which I would load the webpage totalRound times, then within each loading page, I would randomly choose and click button ITER times.
My code structure is like:
let totalRound: number = 10;
let ITER: number = 100;
describe('XX Test', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
describe('Simulate User\'s Click & Unclick',() => {
for(let round = 0; round < totalRound; round++){
it('Click Simulation Round ' + round, () =>{
page.navigateTo('');
let allTagFinder = element.all(by.css('someCSS'));
allTagFinder.getText().then(function(tags){
let isMatched: boolean = True;
let innerTurn = 0;
for(let i = 0; i < ITER; i++){
/* Randomly select a button from allTagFinder,
using async func. eg. getText() to get more info
about the page, then check if the logic is correct or not.
If not correct, set isMatchTemp, a local variable to False*/
isMatched = isMatched && isMatchTemp;
innerTurn += 1;
if(innerTurn == ITER - 1){
expect(isMatched).toEqual(true);
}
}
});
});
}
});
});
I want to get a result after every ITER button checks from a loading page. Inside the for loop, the code is nested for async functions like getText(), etc..
In most time, the code performs correctly (looks the button checkings are in sequential). But still sometimes, it seems 2 iterations' information were conflicted. I guess there is some problem with my code structure for the async.
I thought JS is single-thread. (didn't take OS, correct me if wrong) So in the for loop, after all async. function finish initialization, all nested async. function (one for each loop) still has to run one by one, as what I wish? So in the most, the code still perform as what I hope?
I tried to add a lock in the for loop,
like:
while(i > innerTurn){
;
}
I wish this could force the loop to be run sequentially. So for the async. func from index 1 to ITER-1, it has to wait the first async. finish its work and increment the innerTurn by 1. But it just cannot even get the first async. (i=0) back...
Finally I used promise to solve the problem.
Basically, I put every small sync/async function into separate promises then use chaining to make sure the later function will only be called after the previous was resolved.
For the ITER for loop problem, I used a recursion plus promise approach:
var clickTest = function(prefix, numLeft, ITER, tagList, tagGsLen){
if(numLeft == 0){
return Promise.resolve();
}
return singleClickTest(prefix, numLeft, ITER, tagList, tagGsLen).then(function(){
clickTest(prefix, numLeft - 1, ITER, tagList, tagGsLen);
}).catch((hasError) => { expect(hasError).toEqual(false); });
}
So, each single clicking test will return a resolve signal when finished. Only then, the next round will be run, and the numLeft will decrease by 1. The whole test will end when numLeft gets to 0.
Also, I tried to use Python to rewrite the whole program. It seems the code can run in sequential easily. I didn't met the problems in Protractor and everything works for my first try. The application I need to test has a relatively simple logic so native Selenium seemed to be a better choice for me since it does not require to run with Frond-end code(just visit the webapp url and grab data and do process) and I am more confident with Python.

Reset counter variable on condition

I have this simple "pagination" counter which is fetching the next page from an API. It works fine but the problem is that whenever I change category (movies or series) the counter obviously doesn't reset so instead of fetching the first page of the new category it continues from the number it left off.
I tried numerous conditional combinations but nothing really worked so far. I'm sure it's not that hard to solve I just can't think of the right logic to use.
let page = 1;
document.getElementById('load-more').addEventListener('click', () => {
page++;
const movies = document.getElementById('movies');
const series = document.getElementById('series');
if(movies.classList.contains('active-link')) {
getMovies(page);
} else if (series.classList.contains('active-link')) {
getSeries(page);
}
})
Reseting the let counter inside the if..else doesn't really work because every time I click the load more button it resets it back to page 1.
Use separate variables for the current movies page and the current series page. Also note that you can simplify your logic by using a single querySelector instead of selections followed by classList.contains:
let moviesPage = 1;
let seriesPage = 1;
document.getElementById('load-more').addEventListener('click', () => {
if (document.querySelector('#movies.active-link')) {
moviesPage++;
getMovies(moviesPage);
} else if (document.querySelector('#series.active-link')) {
seriesPage++;
getSeries(seriesPage);
}
});
Set another event listener for the click on your #movies and #series link,
and set the page variable to 1 at this place.
That would be the usual behavior when switching lists, one usually see a reset of paging.

Cannot click button in nightmare.js but works in console

I've successfully navigated to the corresponding page where I want to select multiple elements and click a button to confirm. The selection of the elements work, I've confirmed this with a screenshot, but clicking the button in nightmare does not work. When I run the segment in the console, everything works fine. The button has a randomly defined ID, and everything else except the innerHTML of the button is not unique, so I iterate over all buttons to match it based on content.
It's this snippet that's relevant.
.evaluate(function(){
//Select all the "elements" for room.
var elemArr = document.getElementById("L210").getElementsByTagName("td");
document.getElementById("resRoom").innerHTML = "L210";
document.getElementById("resStartTime").innerHTML = "08:00";
document.getElementById("resEndTime").innerHTML = "19:00";
for(var i = 0; i < elemArr.length; i++){
elemArr[i].className += " selected"
}
//Here select and click the button
var bTags = document.getElementsByTagName("button");
var searchText = "Confirm";
for (var i = 0; i < bTags.length; i++) {
if (bTags[i].innerHTML == searchText) {
bTags[i].click();
break;
}
}
})
Without seeing your full code I can't say for sure, but the most likely answer is that in the context of evaluate your nightmare code ( the .click() ) won't run because it doesn't have access to the original nightmare function. You would either need to use nightmare.click("bTags[i]") or use
.then(function(result){
if(result === "Confirm"){
nightmare.click("bTags[i])"
}
On top of all this - you're using a for loop to call a nightmare action! This is going to cause some issues. Nightmare issues promises before executing. This means you're attempting to run multiple electron instances at the same time, because the promises execute concurrently with the for loop. Rather than queue up - they fight for dominance, causing a crash. You should probably use a generator to manage async code such as vo or co.
Resources:
Common nightmare.js pitfalls

Categories

Resources