Cannot click button in nightmare.js but works in console - javascript

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

Related

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

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!

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.

Waiting for button press within for loop?

I have 2 audio files, this.audio1 and this.audio2. For each trial, the user is supposed to choose whether the two files are the same or different. So, I want to play the two audio files one after each other, wait for the use to click the same or different button, and then go to the next trial. This is my code so far for playing the audio files:
for (var i = 0; i < this.numTrials; i++){
var audio1; // these are actually initialized, obviously, in my code
var audio2;
var noRepeat = true;
audio1.addEventListener('ended', function () {
if (noRepeat) {
audio2.play();
noRepeat = false;
}
});
audio2.addEventListener('ended', function () {
game.audioComplete = true;
});
audio1.play();
// here, I want to add code so it waits until a button is pressed before moving on
}
I tried an eventListener where my comment is, which didn't work (it just kept looping through anyway). Does anyone have any suggestions for what I could use to "pause" the loop and wait for the button press, and then have it move on?
Thanks!
Something like this, this is the same as what #fixatd commented.
var globalPlayCount = 0;
...
function play() {
if(globalPlayCount < this.numTrials) {
globalPlayCount++:
audio1.play();
}
}
...
Fire play() on your button click. Just make sure you have both your event listeners intact.

jquery issue : any css changes before an each loop apply only after

I have some code like following :
LoadingImage.show("#contentpage", urlStk.LoadImg);
var errors = 0;
var ComponentToUpdate = new Array();
var storedItems = JSON.parse(localStorage.getItem("Components"));
$(".myDataGridRow").each(function () {
errors += validateInput(this);
component = {
FamilyCode: $.trim($("td[name=FamilyCode]", this).text())
}
ComponentToUpdate.push(component);
});
LoadingImage.hide("#contentpage");
The $(".myDataGridRow").each()) loop can be a little bit slow. So I try to display some waiting animated gif that overlays on the data grid and its rows (myDataGridRow).
LoadingImage.show() and LoadingImage.hide() methods do work fine when the executed code between is some ajax call to a remote server.
The problem is that the animated gif never appears in this case (the each() loop is only going through HTML elements and performing simpls validations), nor its parent DIV container...
After many tests, it seems that any javascript code written before the each() loop seems to be executed after (I have not tried the alert() case, but any css changes on other elements are blocked till the each() loop finishes, timers declared before are triggered after... ) ??
Forcing the display of the waiting image inside the each loop does not work.
Any help idea will be welcome.
At a guess, your animation isn't playing because the JavaScript is running in the main thread. If you use setTimeout() or setImmediate(), you can run your expensive code in a separate thread, which will allow the browser itself to handle displaying the animation.
Example below:
LoadingImage.show("#contentpage", urlStk.LoadImg);
setImmediate(function () {
var errors = 0;
var ComponentToUpdate = new Array();
var storedItems = JSON.parse(localStorage.getItem("Components"));
$(".myDataGridRow").each(function () {
errors += validateInput(this);
component = {
FamilyCode: $.trim($("td[name=FamilyCode]", this).text())
}
ComponentToUpdate.push(component);
});
LoadingImage.hide("#contentpage");
});

Dynamic Creation of Editors - Does Browser need to exit the function to make the changes?

I am trying to dynamically create and destroy TinyMCE editors like this .
1) It appears that if I put a break point and check for tinymce editors after creation , i.e after the first for loop - I dont see them in the Browser
2) Nor do I see them in tinymce.editors in console
Hence my destroy is not working . However after everything , I can see the editors .
Because the second for loop won't get executed .
Question mainly is , is there something like function has to exit and then browser makes the DOM changes ? If so should I put a sleep ? I got this idea from
What is the JavaScript version of sleep()? i.e Browser makes DOM changes after the function exists or something like that .
Can anyone enligthen me ?
for (var i=0;i<10;i++)
{
//i=0;
divObj = document.createElement('div');
divObj.className = 'top_div';
divObj.id = 'top_div_' + i;
divObj.innerHTML = 'Tiny Editor';
var textareaObj = document.createElement('textarea');
textareaObj.className = 'simpleEdit';
textareaObj.id = 'nic_' + i;
textareaObj.style.cssText="width: 300px; height: 100px;";
divObj.appendChild(textareaObj);
document.body.appendChild(divObj);
tinyMCE.execCommand('mceAddControl', false, textareaObj.id);
}
editors = tinyMCE.editors.length;
for (var i=0;i<editors;i++)
{
tinyMCE.remove(tinyMCE.editors[0]);
}
You are calling the remove function right after you create the editors. Thus, your editor instances have not been fully created - which is the reason for you not finding any instances.
The right way here is to use the tinymce init config param onInit, which gets called when the editor is ready.

Categories

Resources