how to handle click opening new window cypress - 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')

Related

how to access element inside of paypal popup window in cypress

I am working on testing paypal checkout stuff using cypress. But the problem is that when the PayPal popup window opens, I don't know how to access these popup window elements. Can anyone help me to resolve this issue
Without a sample of the html, this will be a generic answer.
You will have to get the iframe of paypal, then drill down to its contents to be able to search within the paypal window elements.
cy.get('iframe')
.its('0.contentDocument.body')
// now you can search within the paypal window
In case you have any clicks you need to do, you may be redirected to another window, in which case you will have to use cy.origin().
cy.origin('paypal.com',
{ args: sentArgs },
({ url }) => {
const path = url.split('com/')
cy.visit(`/${path[1]}`)
)

Outlook Add-in that just directs to a website

I want to program a simple Outlook add-in that opens a browser and take the user to a specific site.
I've had a look at using Yeoman, but this add-in opens a task pane where I'm just looking to take that single actions.
Is there a simple way to do this?
EDIT:
I managed to get this done, but I not have the following issue: I have a single button (via Yeoman's generator) that when clicked executes the following:
function action(event) {
const message = {
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
message: "Window opened.",
icon: "Icon.80x80",
persistent: true,
};
// Show a notification message
window.open("https://myurl.com");
Office.context.mailbox.item.notificationMessages.replaceAsync("action", message);
// Be sure to indicate when the add-in command function is complete
event.completed();
}
I get the following error in Outlook itself:
We deployed the app using the MS 365 admin center, but I'm not sure if there is something additional that I need to do in this case to run the webserver?
There is an Office.js API that will open a browser window:
Office.ui.openBrowserWindow( -- URL string here -- );
This will cause the computers default browser to open to the specified URL. You could have a button in the task pane whose handlers calls this method. Alternatively, you could have a custom button on the ribbon that calls a FunctionFile that calls this method.
If you want to display any web site to the user as a result of the button click or some action on the pane, try doing window.open('https://yoursite.com'). This should work if the domain is whitelisted in your manifest. For example:
function redirectFunction() {
window.open("https://othersite.com")
//window.location.href = "https://othersite.com";
}

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.

Chrome App: launch link in Chrome rather than Safari

I'm developing a Chrome (packaged) app which maintains a set of bookmarks. This opens in its own small window. Clicking on a bookmark opens it in a browser using a link with target set to '_blank'.
On Mac OS X, these open in Safari. Is there anyway of having them open in Chrome?
When you click on a link with target="_blank" in a packaged app, Chrome respects your choice of the default browser and opens the link externally in whatever it is, not necessarily Chrome. In your case, the default system browser must be Safari.
The easy way to open such links in Chrome would be to make it the default browser instead.
If you don't want to do that, but still for some reason insist that your links open in new tabs specifically in Chrome, here is one (perhaps the only) way to achieve that:
Write a companion extension to your app and have your users install it.
In the app, attach an onclick handler to every link, and use chrome.runtime.sendMessage() to send a request to the extension to open the link's URL (in order to do that, you will have to find out your extension's ID and bake it into its manifest, as described here: http://developer.chrome.com/apps/manifest/key.html):
var link = ...;
link.addEventListener('click', function(e) {
e.stopPropagation();
e.preventDefault();
chrome.runtime.sendMessage(
yourExtensionId, { url: link.href }, function(response) {}
);
};
In the extension, define a chrome.runtime.onMessageExternal(data) handler (it will intercept sendMessage() requests from the app), and use chrome.tabs.create() in there to open a new tab:
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
// Don't forget to make sure that |sender| is you app here.
chrome.tabs.create({ url: request.url }, function() {
// If you need to notify the app when the tab opens:
sendResponse(true);
});
// 'true' means that your response is sent asynchronously.
return true;
}
);

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