Cypress: check if new opened tab has correct URL - cypress

If I have a link in my website. Eg. go to Google and I want to make a test:
GIVEN link (html tag a)
WHEN click the link
THEN browser opens new tab and URL of this tab includes 'google.com'
I know that this does not work:
cy.get('a').click();
cy.url().should('include', 'google.com');

Since the a has a target attribute you can do this.
cy.get('a')
.should('be.visible')
.then(($a) => {
expect($a).to.have.attr('target','_blank')
// update attr to open in same tab
$a.attr('target', '_self')
})
.click()
cy.url().should('include', 'google.com')
Depending on your app and what you are wanting to test, using cy.request() and checking on 200 status code may suffice for an external url.

You can use removeAttr to remove target and then click the link and assert. Something like:
cy.get('a').invoke('removeAttr', 'target').click()
cy.url().should('include', 'google.com')

Related

how to handle click opening new window cypress

How to handle the windows in Cypress?
The problem I'm facing is that when I click a button, a new browser window gets opened in a new tab with the actual page to test.
I have tried everything -> window.open and window.location.replace without success (the target _blank is not possible because there is not that tag in the button)
How can I handle that functionality?
Thanks in advance.
The problem is window.open can't be stubbed in the usual (simple) way, a security feature to prevent browser hijack.
This article Stub window.open has an alternative
TLDR - modify the window before it hits the browser
// ✅ CORRECT SOLUTION
it('opens a new window', () => {
// create a single stub we will use
const stub = cy.stub().as('open')
cy.on('window:before:load', (win) => {
cy.stub(win, 'open').callsFake(stub)
})
cy.visit('/')
// triggers the application to call window.open
cy.get('button').click('Open new window')
cy.get('#open').should('have.been.calledOnce')
I found many different approaches to stubbing the window.open call, but none of them worked out of the box.
In my use case there's a button that launches a click event. The click event then opens a new tab with a dynamic url that I wanted to grab.
The answer is a mix of a great post: https://glebbahmutov.com/blog/stub-window-open/ and Cypress: Stub open window.
This example should work with Cypress 10.x
// Listen to window:before:load events, modify the window object before the app code runs between page transitions
// Create a stub with the alias windowOpen, choose whatever you like
// Grab the url parameter that the page was trying to open and visit the page
cy.on('window:before:load', (win) => {
cy.stub(win, 'open').as('windowOpen').callsFake(url => {
cy.visit(url);
})
})
// Start by visiting the page you'll run your tests in. I'm using the baseUrl here.
cy.visit("/");
// Do whatever tests need to be done before the action the opens a new tab
// Now the element that fires a click event which then uses window.open to open a new tab
cy.contains("Ok").click();
// The stub should now have picked the url and called cy.visit(url)
// The page that would normally open in a new tab, should be visible in the same page
// Now the next commands are intended to run in the new page and should be able to complete
cy.get(".whateverselectoryouwant")
.should('have.text', 'whateveryourtextisonthenewpage')

Cypress: Prevent open new tab with link dynamically created and clicked

I want to test a file download. It is made programmatically on click a button that uses this function:
export function downloadURI(uri, target) {
const link = document.createElement('a')
if (target) link.target = target
link.href = uri
link.click()
}
The problem is that when you do cy.click() on that button the new tab is opened and the tests fail. I am checking that the download is successful by asserting the loading modal is visible after clicking the button (while the file is being generated via an HTTP request) and is Not visible after the download was generated.
How can I prevent this tab from opening so that the tests do not fail?
This works for me:
cy.get('a').invoke('removeAttr', 'target').click()
From the official document it says that cypress does not support multiple tabs testing.
Also there is a recipe including 3 solutions about how to handle this.
Have a read and see if it can help.

Is it possible to force fail a recaptcha v2 for testing purposes? (I.e. pretend to be a robot)

I'm implementing an invisible reCAPTCHA as per the instructions in the documentation: reCAPTCHA V2 documentation
I've managed to implement it without any problems. But, what I'd like to know is whether I can simulate being a robot for testing purposes?
Is there a way to force the reCAPTCHA to respond as if it thought I was a robot?
Thanks in advance for any assistance.
In the Dev Tools, open Settings, then Devices, add a custom device with any name and user agent equal to Googlebot/2.1.
Finally, in Device Mode, at the left of the top bar, choose the device (the default is Responsive).
You can test the captcha in https://www.google.com/recaptcha/api2/demo?invisible=true
(This is a demo of the Invisible Recaptcha. You can remove the url invisible parameter to test with the captcha button)
You can use a Chrome Plugin like Modify Headers and Add a user-agent like Googlebot/2.1 (+http://www.google.com/bot.html).
For Firefox, if you don't want to install any add-ons, you can easily manually change the user agent :
Enter about:config into the URL box and hit return;
Search for “useragent” (one word), just to check what is already there;
Create a new string (right-click somewhere in the window) titled (i.e. new
preference) “general.useragent.override”, and with string value
"Googlebot/2.1" (or any other you want to test with).
I tried this with Recaptcha v3, and it indeed returns a score of 0.1
And don't forget to remove this line from about:config when done testing !
I found this method here (it is an Apple OS article, but the Firefox method also works for Windows) : http://osxdaily.com/2013/01/16/change-user-agent-chrome-safari-firefox/
I find that if you click on the reCaptcha logo rather than the text box, it tends to fail.
This is because bots detect clickable hitboxes, and since the checkbox is an image, as well as the "I'm not a robot" text, and bots can't process images as text properly, but they CAN process clickable hitboxes, which the reCaptcha tells them to click, it just doesn't tell them where.
Click as far away from the checkbox as possible while keeping your mouse cursor in the reCaptcha. You will then most likely fail it. ( it will just bring up the thing where you have to identify the pictures).
The pictures are on there because like I said, bots can't process images and recognize things like cars.
yes it is possible to force fail a recaptcha v2 for testing purposes.
there are two ways to do that
First way :
you need to have firefox browser for that just make a simple form request
and then wait for response and after getting response click on refresh button firefox will prompt a box saying that " To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier. " then click on "resend"
by doing this browser will send previous " g-recaptcha-response " key and this will fail your recaptcha.
Second way
you can make any simple post request by any application like in linux you can use curl to make post request.
just make sure that you specify all your form filed and also header for request and most important thing POST one field name as " g-recaptcha-response " and give any random value to this field
Just completing the answer of Rafael, follow how to use the plugin
None of proposed answers worked for me. I just wrote a simple Node.js script which opens a browser window with a page. ReCaptcha detects automated browser and shows the challenge. The script is below:
const puppeteer = require('puppeteer');
let testReCaptcha = async () => {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.goto('http://yourpage.com');
};
testReCaptcha();
Don't forget to install puppeteer by running npm i puppeteer and change yourpage.com to your page address

Open hangout in new tab

I've integrated a hangout button into my website. When I click it a child window is opened. Is it possible to make hangout opened in current tab or in a new tab (like a usual link does)?
I've looked through Hangout Button documentation but haven't found anything like this (while I believe I saw it somewhere over the Internet).
Update There was a couple of examples how you can specify a new hangout url without Hangout Button in the answers and comment. But no proves were provided that this is a reliable way and no documentation was provided about the ways to specify additional parameters (e. g. startDate for Hangout App).
Update 2 I've found that when you create a new hangout app Google Develope Console provides a Hangout link:
with the following url: https://hangoutsapi.talkgadget.google.com/hangouts?authuser=0&gid=appId. Does it work only for sandbox? Is there any way to specify other parameters like startData?
I use the following to open hangout in a new tab
<a target="_blank" href="https://plus.google.com/hangouts/_?gid=<app_id">Start a Hangout</a>
Use the query parameter gd=somevalue to pass your app an initial set of data
https://developers.google.com/+/hangouts/running#passing-data
I send start data like this
https://plus.google.com/hangouts/_?gid=<app_id">&gd=<start_data>
and also like this
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div id="placeholder-rr"></div>
<script>
gapi.hangout.render('placeholder-rr', {
'render': 'createhangout',
'initial_apps': [{'app_id' : 'Your app_id', 'start_data' : 'Put your start data here', 'app_type' : 'ROOM_APP' }],
'widget_size': 175
});
</script>
Checked the documentation, doesn't seem that the button is meant to be flexible with configuration.
If you're looking for a coding solution apart than:
gapi.hangout.render('placeholder-div', {
'render': 'createhangout',
'initial_apps': [{'app_id' : '184219133185', 'start_data' : 'dQw4w9WgXcQ', 'app_type' : 'ROOM_APP' }],
'widget_size': 200
});
Deferred execution and language configuration:
window.___gcfg = {
lang: 'zh-CN',
parsetags: 'onload'
};
not much can be done.
On the manual side, holding ⌘ (CTRL on windows) while clicking on the button will open the hangout in a new tab instead.
Tested successfully on Chrome and Safari.
Unsuccessful on Firefox.
There is a plain link button available:
https://hangoutsapi.talkgadget.google.com/hangouts/_?gid=APP_ID
You can simply open this link in a new tab:
Hangout

WatiN driving the IE "Are you sure you want to leave this page?" popup

I'd like to extend my WatiN automated tests to drive a page that guards against the user accidentally leaving the page without saving changes.
The page uses the "beforeunload" technique to seek confirmation from the user:
$(window).bind('beforeunload', function (event) {
if (confirmationRequired) {
return "Sure??";
}
});
My WatIn test is driving the page using IE. I cannot find a way to get WatIn to attach to the popup dialog so I can control it from my test.
All the following have failed (where the hard-coded strings refer to strings that I can see on the popup):
Browser.AttachTo<IE>(Find.ByTitle("Windows Internet Explorer");
browser.HtmlDialog(Find.FindByTitle("Windows Internet Explorer));
browser.HtmlDialog(Find.FindByTitle("Are you sure you want to leave this page?));
browser.HtmlDialog(Find.FindFirst());
Thanks!
You'll need to create and add the dialog handler.
Example Go to example site, click link, click leave page on confirmation dialog:
IE browser = new IE();
browser.GoTo("http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/onbeforeunload.htm");
WatiN.Core.DialogHandlers.ReturnDialogHandlerIe9 myHandler = new WatiN.Core.DialogHandlers.ReturnDialogHandlerIe9();
browser.AddDialogHandler(myHandler);
browser.Link(Find.ByUrl("http://www.microsoft.com")).ClickNoWait();
myHandler.WaitUntilExists();
myHandler.OKButton.Click();
browser.RemoveDialogHandler(myHandler);
The above is working on WatiN2.1, IE9, Win7. If using IE8 or before, you will likely need to use the ReturnDialogHandler object instead of the Ie9 specific handler

Resources