How to open new browser window in intern js? - javascript

I am automating the UI test of my application. There are some cases when i want my test script to close the current browser and and run next test by opening new browser. The problem is that I am unable to figure out how to open new browser window in intern. remote.get(URL) doesn't do what i want to do here. Can someone please help.
I have updated my question to include code as well. My question is pretty much straight forward though. How to open new browser window using intern from inside test ?.
though if you want to see the code please comment, I will write it down .
Thanks.
// in tests/functional/index.js
define([
'intern!object',
'intern/chai!assert',
'Automation/ConfigFiles/dataurl',
'Automation/pages/login/loginpage',
'intern/dojo/node!fs',
'intern/dojo/node!leadfoot/helpers/pollUntil'
], function (registerSuite, assert, dataurl, LoginPage, fs, pollUntil) {
registerSuite(function () {
var loginPage;
var values;
return {
setup: function () {
var data = fs.readFileSync(loginpage, 'utf8');
json = JSON.parse(data);
values = json.values;
loginPage = new LoginPage(this.remote, json.locator);
return this.remote
.get(require.toUrl(json.locator.URL)).setFindTimeout(60000000000).sleep(5000)
},
beforeEach:function() {
// here i want to open new window
},
'valid loginname lands to password page':function () {
loginPage.submitLoginName(values.unamevalue);
loginPage.isPasswordPageDisplayed().then(function(isPasswordPageDisplayed) {
assert.true(isPasswordPageDisplayed, 'password page is not displayed, Invalid Login name');
})
},
'successful login': function () {
loginPage
.login(values.unamevalue, values.pwdvalue)
loginPage.isLoginSuccess().then(function (loginSuccess) {
assert.isTrue(loginSuccess, 'Login Failed');
});
},
afterEach: function () {
return this.remote.closeCurrentWindow()
}
};
});
});

You can open a new window with window.open. The trick is that you want to run that command in the remote browser. Intern (technically Leadfoot) gives you two methods for doing that on this.remote: execute and executeAsync. For example, to simply open a new window, you could do:
this.remote.execute(function () {
window.open();
})
Once you've opened a new window, you need to switch to it to interact with it. A script might look something like:
var windowHandles;
this.remote
.getAllWindowHandles()
.then(function (handles) {
windowHandles = handles;
})
.execute(function () { window.open() })
.sleep(500)
.getAllWindowHandles()
.then(function (handles) {
// compare the new handles to windowHandles to figure out which
// is the new window, then switch to it
return this.remote.switchToWindow(newWindowHandle);
})
.get('some_new_url')
// rest of test

Related

Can I emulate/provoke failure to copy to clipboard from JS in Chrome?

I have a web page with some JavaScript code that copies stuff to the clipboard similar to what this demo does: https://davidwalsh.name/demo/javascript-copy-clipboard.php
My code is something like this:
// Within a listener that is triggered by a click on some button:
var copiedText = "...something";
navigator.clipboard.writeText(copiedText).then(
function() {
console.log("Succesfully copied");
},
function() {
console.log("FAILED to copy!!!!!!");
}
);
This works fine, but it always succeeds. I need to test that the behavior is correct when copying fails for whatever reason.
How can I cause the copy to fail on purpose so that I can test the behavior of my code in that situation?
I never get a prompt asking me permission to write to the clipboard.
In Chrome, I have tried going to the site settings for the site, and under "Clipboard" selecting "Block", but it does nothing (I guess that's only for reading from the clipboard).
Sure, just provide an invalid argument which will throw an exception during the stringification algorithm:
Note that this demo will work in your own page, but the success case won't work in the Stack Overflow code snippet iframe sandbox (where there is no clipboard permission).
function copyThenLog (input) {
navigator.clipboard.writeText(input).then(
() => console.log({success: true}),
(ex) => {
console.log({success: false});
console.error(ex);
},
);
}
document.querySelector('.success').addEventListener('click', () => {
const input = 'hello world';
copyThenLog(input);
});
document.querySelector('.fail').addEventListener('click', () => {
const input = {
toString () {
throw new Error('Oops');
}
};
copyThenLog(input);
});
<div class="success">Click me to succeed</div>
<div class="fail">Click me to fail</div>

Cypress: Stub open window

in my app there is an recommendations list, which on click opens a new window with a dynamic address:
$window.open(_shopURL, '_blank');
Now I'm trying to stub the windows.open event as shown in https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/stubbing-spying__window/cypress/integration/window-stubbing.spec.js
Cypress.on('window:before:load', (win) => {
win.open = cy.stub().as('windowOpen')
})
describe('Shop integration', () => {
beforeEach(function () {
cy.visitHome(countryCode, resellerId)
})
it('can stub the window open event', function () {
cy.get(`.recommendations-list .recommendations-cover:nth-of-type(1)`)
.click()
cy.get('#windowOpen').should('be.calledWith', 'page1.html')
})
But it's always opening the new tab and the logs are wrong:
Cypress: stub open window
Does anybody has an idea why it's not working?
Cheers!
Code below will help you to stub window.open and further assert it that function has been triggered:
it('opens the about page', () => {
cy.visit('/')
cy.window().then(win => {
cy.stub(win, 'open').as('Open')
})
cy.get('.your-selector').click()
cy.get('#Open').should('have.been.calledOnceWithExactly', yourUrl)
})
You also can stub window.open in cy.on hook as you did, what helps you to yield new window object each time after page reload. However, if you want to actually open the new Url in existing tab instead of new one you can use this code below by passing "_self" param to overwrite old "_blank":
cy.window().then(win => {
cy.stub(win, 'open').callsFake((url) => {
return win.open.wrappedMethod.call(win, url, '_self');
}).as('Open');
});
callsFake function dynamically withdraws url which has been placed into original window.open(url, "_blank"), or you can manually change url inside .call(win, url, '_self'); with static one, so regardless on which link or button you clicked, which triggers window.open, they all will open the same url.
I'm using page-objects for every page I want to test. So in my parent page-object which gets inherited by every other PO I do the following when opening a url:
public navigateTo(url: string, defaultTimeout: number = 5000) {
return cy.visit(url, {
onBeforeLoad: (win: any) => {
cy.stub(win, 'open');
},
timeout: defaultTimeOut
});
}
This prevents window to open a new page.
You also can use this easy way:
const newUrl = 'your url';
cy.window().then((win) => {
cy.stub(win, 'open').callsFake(url => {
newUrl = url
}).as('windowOpen')
})
cy.get('your path').click()
cy.get('#windowOpen').should('be.called')
cy.visit(newUrl)

How to close print windows dialog in Protractor Test

I am doing end-to-end testing with protractor. In a certain test, I need to test like print button is creating pdf or not. So When Test clicks the button, It opens the print window dialog like below.
And now this test is not able to be finished. because of this print window. My question is how to close this print dialog in protractor? Because of it, rest of test become pending. Please help. Thanks in advance.
EDIT
I have tried like this..
var printButton=element(by.css('[class="print"]'));
/* This print button should be present first*/
expect(printButton.isPresent()).toBe(true);
browser.actions().mouseMove(printButton).perform();
printButton.click().then(function () {
// fill in the form here
browser.sleep(2000);
// For Pressing Escape key
browser.actions().sendKeys(protractor.Key.ESC).perform();
});
I thought If i got successful to press escape key, then It will resolve the issue.But No Success.
NEXT EDIT--
I have tried new Windows change like below
printButton.click().then(function () {
// fill in the form here
browser.sleep(4000);
browser.getAllWindowHandles().then(function(handles){
browser.switchTo().window(handles[1]).then(function(){
//do your stuff on the pop up window
browser.driver.close();
browser.switchTo().window(handles[0]);
});
});
});
but it shows an error in console and actually It does not open any windows. and hungs up on print dialog as previous.
Failed: unknown error: failed to close window in 20 seconds
EDIT 3
I am having this problem in angular js not in java.
EDIT 4 My Last Attempt
printButton.click().then(function () {
// fill in the form here
return browser.getAllWindowHandles().then(function (handles) {
var newWindowHandle = handles[1]; // this is your new window
return browser.switchTo().window(newWindowHandle).then(function () {
return browser.sleep(5000).then(function () {
return browser.actions().sendKeys(protractor.Key.ESCAPE).perform().then(function () {
return browser.switchTo().window(handles[0])
});
});
});
});
But It does not open a new tab for print Dialog..open print Dialog in same tab.
You need to send the escape to the right window. Also wait for the window to be open before you send it. You probably also need to switch back to handles[0].
return browser.getAllWindowHandles().then(function (handles) {
var newWindowHandle = handles[1]; // this is your new window
return browser.switchTo().window(newWindowHandle).then(function () {
return browser.sleep(5000).then(function () {
return browser.actions().sendKeys(protractor.Key.ESCAPE).perform().then(function () {
return browser.switchTo().window(handles[0])
});
});
});
});
Set the capabilities as below; this will disable the print preview pop up from chrome browser
capabilities: {
'browserName': 'chrome',
chromeOptions: {
args: ['--disable-print-preview','start-maximized']
}
},

NightwatchJS .waitForElementPresent abortOnFailure not working

I'm using NightwatchJS with NodeJS: http://nightwatchjs.org/api
I have a modal dialog, which may or may not appear. It has a #close_button that needs to be clicked (if the modal does appear) to continue.
I set the abortOnFailure parameter of waitForElementPresent to false so the script continues if the modal does not appear. However I can't get it to work.
Any suggestions?
module.exports = {
"Test" : function (browser) {
browser
.url("http://domain.com/")
.waitForElementPresent('#close_button', 5000, false, function() {
this.click('#close_button')
})
.setValue('#username', 'test#email.com')
//more code here
.end(); //does end() go here or inside .waitForElementPresent() above?
}
}
abortOnFailure works fine, however waitForElementPresent has a bug now in which the callback you passed it's not called in the correct context. That will be fixed.
In the mean time you can write your test like this, with placing the click outside, which is the same thing and looks cleaner:
module.exports = {
"Test" : function (browser) {
browser
.url("http://domain.com/")
.waitForElementPresent('#close_button', 5000, false)
.click('#close_button')
.setValue('#username', 'test#email.com')
//more code here
.end(); // end() goes here
}
}
I ran into something similar, I was waiting for an iframe to be present. I created a function to actually close it:
pageObject function:
Home.prototype.closeIframe = function(browser) {
var self = this;
console.log('Checking for iframe');
this.browser
.isVisible(iframeSelectors.iframe, function(result) {
if (result.value === true) {
self.browser
.log('iframe visible')
.frame(iframeSelectors.name)
.waitForElementVisible(iframeSelectors.closeLink)
.click(iframeSelectors.closeLink)
.assert.elementNotPresent(iframeSelectors.iframe)
.frame(null)
.pause(2000); //allow for proper frame switching
} else {
console.log('iframe is not visible');
}
});
return this;
In my test I wait for the page to fully load before executing the above function.

Protractor E2E Testing Error : Object [object Object] has no method 'getWindowHandle'

I am trying to check the pop up for facebook login opening on click of button .
Error : Object [object Object] has no method 'getWindowHandle'.
Code Snippet generating error :
describe('Tests', function() {
var ptor;
var handlePromise;
var util = require('util');
beforeEach(function() {
ptor = protractor.getInstance();
handlePromise = ptor.getAllWindowHandles();
var handlesDone = false;
ptor.get('/SiteB_Upgrade_Device/app/index.html#/Recommendations#page');
ptor.findElement(by.id('fb')).click();
ptor.ignoreSynchronization = true;
});
describe('login', function() {
return it('should switch to popUp\'s handle', function() {
handlePromise.then(function(handles) {
var popUpHandle = handles[0];
var handle = browser.driver.switchTo().window(popUpHandle).getWindowHandle();
expect(handle).toEqual(popUpHandle);
});
},30000);
});
});
Here is what I currently use to navigate through popups/tabs :
// do stuff that will trigger the popup
// ...
browser.getAllWindowHandles().then(function (handles) {
// switch to the popup
browser.switchTo().window(handles[1]);
// make sure the popup is now focused
expect(browser.getCurrentUrl()).toEqual('popup/url');
// do stuff with the popup
// ...
// go back to the main window
browser.switchTo().window(handles[0]);
// make sure we are back to the main window
expect(browser.getCurrentUrl()).toEqual('original/url');
});
You just need to make sure that your popup is really a new window and not juste some kind of popover ( in which case you can just target it with css selectors ).
Another thing to keep in mind when you change tabs/popups it that the target page might not have angularjs loaded in it, which will render protractor useles. If you face this case you can simply use browser.driver as a replacement for browser to navigate a non angular page.
Hope this helps.

Categories