in Cypress i can not make the command 'promt' to work - cypress

I am doing API testing with Cypress and I want to have a prompt that asks for a value.
I use a function to try to get the value.
The commands: Alert and Confirm shows a popup windows, but Prompt (or window.prompt) does not work (nothing shows/no error message)
How can I get the Prompt to work?
My tests are:
Image:
Here is the code:
///
describe('Example to demonstrate handling of JavaScript Alerts, Confirm, Prompt in Cypress', () => {
console.clear()
it('get answer ', () => {
var answer = window.confirm("Would like to confirm?");
if (answer) {
console.log('YES')
}
else {
console.log('NO')
}
});
it('get answer ', () => {
var name = alert("Your name is Null");
console.log(name)
});
it('get answer ', () => {
var name = prompt("What is your name?");
console.log("Hi " + name)
});
})

Related

Cypress: Getting Cypress detected that you invoked one or more cy commands in a custom command but returned a different value

While returning any single /set of values from a function (from command.js /Page object class) getting error as "Cypress detected that you invoked one or more cy commands in a custom command but returned a different value.". I have searched different options like 'Warp', '.then' but not have the luck.
Following are the details:
My Command.js file:
Cypress.Commands.add("getconstantvalue", () => {
const todaysDateTime = Cypress.moment().format('MMMDDYYYYSS')
cy.log(todaysDateTime)
return todaysDateTime
})
and I want this 'todaysDateTime' in my driver/describe suit script:
describe('The Home Page', function() {
it('successfully loads', function() {
var data = cy.getconstantvalue()
cy.log(data)
})
})
This should work. You just have to chain it to the command you are using.
Command.js File
Cypress.Commands.add("getconstantvalue", () => {
const todaysDateTime = Cypress.moment().format('MMMDDYYYYSS')
cy.log(todaysDateTime)
return cy.wrap(todaysDateTime)
})
Test File
describe('The Home Page', function() {
it('successfully loads', function() {
cy.getconstantvalue().then(data => {
cy.log(data);
})
})
})

Cypress custom command wont return value

I have a function that I want to add as a command so i can reuse it.
Its on cypress/support/commands.js:
Cypress.Commands.add("generatePassword", () => {
return 'randomstring';
}
);
Then on my test I want to use it as:
it("Visits page", () => {
const password = generatePassword();
cy.log({password})
// Here it logs this:
//{password: {chainerid: chainer146, firstcall: false}}
});
Any idea on how to get the actual value? Now i get this:
{chainerid: chainer146, firstcall: false}
Thanks.
Basically cypress works in promise chain and you're returning the promise chainerid from your custom command. You have to chain it to use in next statement. Use something like below.
it("Visits page", () => {
return cy.generatePassword().then(pwd => {
cy.log(pwd);
});
});

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?

The way i am polling tasks for async POST call, is it correct??? Because program control doesn't enter 'while' loop in spec file. Please help!
Previous query: How to return a value from Cypress custom command
beforeEach(function () {
cy.server()
cy.route('POST', '/rest/hosts').as("hosts")
})
it('Create Host', function () {
let ts =''
let regex = /Ok|Error|Warning/mg
// Some cypress commands to create a host. POST call is made when I create a host. I want to poll
// task for this Asynchronous POST call.
cy.wait("#hosts").then(function (xhr) {
expect(xhr.status).to.eq(202)
token = xhr.request.headers["X-Auth-Token"]
NEWURL = Cypress.config().baseUrl + xhr.response.body.task
})
while((ts.match(regex)) === null) {
cy.pollTask(NEWURL, token).then(taskStatus => {
ts= taskStatus
})
}
})
-------------------------
//In Commands.js file, I have written a function to return taskStatus, which I am using it in spec
file above
Commands.js -
Cypress.Commands.add("pollTask", (NEWURL, token) => {
cy.request({
method: 'GET',
url: NEWURL ,
failOnStatusCode: false,
headers: {
'x-auth-token': token
}
}).as('fetchTaskDetails')
cy.get('#fetchTaskDetails').then(function (response) {
const taskStatus = response.body.task.status
cy.log('task status: ' + taskStatus)
cy.wrap(taskStatus)
})
})
You can't use while/for loops 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 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.
With recursion, you can simulate loops.
Add this to your custom commands file (/cypress/support/commands.js):
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);
}
});
});
On your tests, just define a function that does what you want for one iteration, and return false if you don't want to iterate again.
cy.recursionLoop(times => {
cy.wait(1000);
console.log(`Iteration: ${times}`);
console.log('Here goes your code.');
return times < 5;
});
while loop is not working for me, so as a workaround I did a for loop, a sort of while loop with a timeout of retries
let found = false
const timeout = 10000
for(let i = 0; i<timeout && !found;i++){
if(..){
// exiting from the loop
found = true
}
}
it is not helpful for everyone, I know.

Jasmine Protractor: Test case failing when run with grep option

I created few test cases in jasmine/protractor. When i run these using
protractor conf.js
all test case run and pass successfully.
But when i run using
protractor conf.js --grep="dummytag3"
then selected test case get executed, but it fails. I am finding it really strange that why a test case may fail with tagging and pass without tagging.
spec.js
'use strict';
var HomePage = require('./pages/homePage.js');
var BusPage = require('./pages/busPage.js');
describe('Login cases' , function() {
var homePage= new HomePage();
it('Login without username & password #dummytag3' , function() {
homePage.mainLoginButtonClick();
homePage.popupLoginButtonClick();
expect(homePage.errMsgUsername).toEqual('Please enter valid Email or Mobile Number');
});
});
homePage.js
'use strict';
var HomePage = function () {
browser.get('https://www.mobikwik.com');
browser.driver.manage().window().maximize();
};
HomePage.prototype = Object.create({}, {
//Login
mainLoginButton: { get: function () { return element(by.id('qa-mbkLogin')); }},
mainLoginButtonClick: { value: function () { this.mainLoginButton.click(); }},
popupLoginButton: { get: function () { return element(by.xpath('//*[#id="loginInfo"]/div[3]/p/button')); }},
popupLoginButtonClick: { value: function () { this.popupLoginButton.click(); }},
errMsgUsername: { get: function () { return element(by.xpath('//*[#id="loginInfo"]/div[1]/span')).getText(); }},
});
module.exports = HomePage;
error:
Error: Error while waiting for Protractor to sync with the page: "window.anular is undefined. This could be either because this is a non-angular page or ecause your test involves client-side navigation, which can interfere with Protactor's bootstrapping. See http://git.io/v4gXM for details"

How can I add headings to my protractor-jasmine2-screenshot-reports?

I am sharing my spec file, the generated report contains only 'through Gmail Account' text but I want to add 'Password pop up' text and many other headings also. I tried by adding one more 'it' block containg passoword code but my code was not working.
I want to make report shows the headings for all test cases.
My spec file is:
describe('Login', function () {
afterEach(function () {
browser.ignoreSynchronization = false; });
it(' through Gmail Account', function () {
var GM = protractor.ExpectedConditions;
browser.get("http://folio3.github.io/eCareVault/#");
//browser.driver.manage().window().maximize();
var gmail = element(by.css('.ggl>img'));
browser.wait(GM.visibilityOf(gmail), 5000);
gmail.click();
browser.getAllWindowHandles().then(function (handles) {
browser.switchTo().window(handles[1]);
element(by.id("Email")).click();
element(by.id("Email")).sendKeys('cc0#gmail.com');
element(by.id("next")).click();
element(by.id("Passwd")).click();
element(by.id("Passwd")).sendKeys('click123');
element(by.id("signIn")).click();
browser.switchTo().window(handles[0]);
//Password popup
var Password = element(by.model("anyvalue"));
browser.wait(GM.visibilityOf(Password), 10000);
Password.sendKeys("123");
element(by.id("submit")).click();
element(by.css('.overview' )).click();
element(by.css('.edit' )).click(); element(by.xpath('html/body/div[1]/div/form/div/section[1]/div/div[1]/div/input')).click().clear().sendKeys('bob');
});
});
});

Resources