Running multiple browser instances in the same test spec - testing

If I have a single spec that is using page object model, how do I run multiple browser instance for that same spec?
For example I have spec:
it('should run multi browser', function() {
browser.get('http://example.com/searchPage');
var b2 = browser.forkNewDriverInstance();
b2.get('http://example.com/searchPage');
var b3 = browser.forkNewDriverInstance();
b3.get('http://example.com/searchPage');
SearchPage.searchButton.click();
b2.SearchPage.searchButton.click(); //fails here
b3.SearchPage.searchButton.click();
});
How do I reuse vars declared in the SearchPage page object for the other browser instances?

This is a really interesting question that is not covered in Using Multiple Browsers in the Same Test or in the interaction_spec.js.
The problem with page objects is that page object fields are usually defined with a globally available element or browser which in your case would always point to the first browser instance. But you basically need to call element() using a specific browser:
b2.element(by.id('searchInput'));
instead of just:
element(by.id('searchInput'));
FYI, element is just a shortcut for browser.element.
I am really not sure whether this is a reliable solution and would actually work, but you can redefine global element this way. Think about it as switching the search context to different browser instances:
SearchPage.searchButton.click();
global.element = b2.element;
SearchPage.searchButton.click();
global.element = b3.element;
SearchPage.searchButton.click();
global.element = browser.element;

Related

How to use module.exports and requireJS?

im quite a noob in html and js, so forgive me if this is a dumb question but, im trying to use requireJs to export modules in node and i can't get the function work right.
here is the code extracted from example.
first i have this main.js, as the note in the documentation says http://requirejs.org/docs/node.html#2
var sayHi = require(['./greetings.js'], function(){});
console.log(sayHi);
and a greetings.js who export the answer
module.exports= 'Hello';
});
and get nothing as result, so i define the exports and modules
define( function(exports,module){
module.exports= 'Hello';
});
and get as result:
function localRequire()
what am i doing wrong? i read the documentation and examples, but somehow i can't make this works.
I'm assuming the require call you are using is RequireJS's require call, not Node's require. (Otherwise, you'd get a very different result.)
You are using the asynchronous form of the require call. With the asynchronous form, there is no return value for you to use, you have to use the callback to get module values, like this:
require(['./greetings.js'], function(sayHi){
console.log(sayHi);
});
However, because you are running in Node, you can do this:
var sayHi = require('./greetings.js');
Note how the first argument is a string, not an array of dependencies. This is the synchronous form of the require call. The returned value is the module you required. When you are in Node, RequireJS allows you to call this synchronous form anywhere. When you are running the browser, it is only available inside a define call.

Leadfoot + sauce: mapping a collection of elements using getAttr fails in mobile only

My use case varies for this, but in general i'm trying to collect a bunch of elements and then apply _.map() to each. The problem is that this series of .getAttribute() calls can cause a test that works locally to fail against a remote server like sauce/android.
One example: collecting all <div class='article'><a href='articles/{id}'> on a page and then getting the hrefs. it might look something like this, and this approach will work until i test on a mobile (android) sauce environment. then I get a timeout.
Is it possible this is an issue related to my android environment capabilities? To piling up so many requests? I've tried scaling my test down from using 75 articles to only 45 and i've upped the timeout to 60s and still the mobile test fails. locally with chromedriver is fine, chrome desktop + sauce is fine.
Not my actual test but an approximation of the code i'm talking about:
/// ... return this.remote
.findAllByTagName('div.article a')
.then(function (articles) {
var promises = articles.map(function(article) {
return article.getAttribute('href');
});
Promise.all(promises)
.then(function (hrefs) {
uniques = _.uniq(hrefs);
assert(hrefs.length === uniques.length);
});
});
Since you're seeing a timeout error, I'd suggest continuing to increase the test timeout until the test passes. The mobile testing environments on Sauce are both slower to initialize and slower to operate than the desktop environments, so it's quite possible that a test with many requests is simply very slow.
One way to speed things up would be to use an execute block to gather the references, like:
.then(function (articles) {
return this.parent.execute(function (articles) {
return articles.map(function (node) {
return node.getAttribute('href');
});
}, [ articles ]);
})
In the above snippet, the articles element array is passed as an argument to the execute block. The remote WebDriver will deserialize the element references into actual DOM elements that can be operated on in the execute code. This is significantly more efficient than using individual getAttribute requests for each element since only a single request will be made to the remote browser.

Access window object / browser scope from protractor

I'm running tests with protractor, but it seems impossible to access the JS 'window' object. I even tried adding a tag in my html file that would contain something like
var a = window.location;
and then try expect(a) but I couldn't make it work, I always get undefined references...
How should I process to access variables that are in the browser scope ?
Assuming you are using a recent version of Protractor, let's say >= 1.1.0, hopefully >= 1.3.1
Attempting to access Browser side JS code directly from Protractor won't work because Protractor runs in NodeJS and every Browser side code is executed through Selenium JsonWireProtocol.
Without further detail, a working example:
browser.get('https://angularjs.org/');
One-liner promise that, as of today, resolves to '1.3.0-rc.3'
browser.executeScript('return window.angular.version.full;');
You can use it directly in an expect statement given Protractor's expect resolves promises for you:
expect(browser.executeScript('return window.angular.version.full;')).
toEqual('1.3.0-rc.3');
Longer example passing a function instead of a string plus without expect resolving the promise for you. i.e. for more control and for doing some fancy thing with the result.
browser.driver.executeScript(function() {
return window.angular.version.full;
}).then(function(result) {
console.log('NodeJS-side console log result: ' + result);
//=> NodeJS-side console log result: 1.3.0-rc.3
});

How to remember variables with Greasemonkey script when a page reloads

Ive got an problem currently on an mobile site that i'm running directly in my pc's firefox browser. Everytime a button is clicked, the page reloads, thus resetting my variables. I've got this script:
// ==UserScript==
// #name trada.net autoclick 55_1min_mobile
// #namespace airtimeauction auto click
// #include http://www.trada.net/Mobile/
// #version 0.1
// #description Automatically click // ==/UserScript==
var interval = 57000;
var bidClickTimer = setInterval (function() {BidClick (); }, interval);
var numBidClicks = 0;
function BidClick ()
{var bidBtn1=document.getElementById("ctl00_mainContentPlaceholder_AirtimeAuctionItem7_btn_bidNow");
numBidClicks++;
if (numBidClicks > 500)
{
clearInterval (bidClickTimer);
bidClickTimer = "";
}
else
{
bidBtn1.click (1);
}
};
BidClick();
It should click the button every 57 seconds, but the moment it clicks the button, the page reloads, thus resetting the variables. How can i get greasemonkey to "remember" or carry over the variables to the next page/script when it reloads? Will it have something to do with GM_setValue? It will only be this few variables, but the second problem or question wil be, will it subtract the few seconds it takes the page to reload from the "57" seconds? How do i compensate for that?
In addition to GM_setValue...
you also can use the new Javascript "localStorage" object, or a SQL Javascript API.
The advantage of the SQL approach is it is very meager in its resource consumption in a script (think about it; rather than concatenating a humongous string of results, you can tuck away each result and recall it if needed with a precise query. The downside is you have to set up a SQL server, but using something like SQLite that's not a big deal these days. Even postgres or mysql can be quickly spun on a laptop...
Yes, I think you have to use GM_setValue/GM_getValue.
And if you have to do something exactly every 57 seconds, then calculate the time when the next action should take place after the reload, and store it using GM_setValue.
When your script starts, read first if the next action is stored, if it is, use that time to schedule the next action, and calculate the time for the action after that, and so on...
GM.setValue will set a value indefinitely and is scoped to the script, but will work if your script runs across multiple domains.
window.localStorage will set a value indefinitely and is scoped to the domain of the page, so will not work across domains, but will work if you need several GreaseMonkey scripts to access the same value.
window.sessionStorage will set a value only while the window or tab is open and is scoped to only that window or tab for that domain.
document.cookie can set a value indefinitely or only while the browser is open, and can be scoped across subdomains, or a single domain, or a path, or a single page.
Those are the main client-side mechanisms for storing values across page loads that are intended for this purpose. However, there is another method which is sometimes possible (if the page itself is not using it), and can also be quite useful; window.name.
window.name is scoped to the window or tab, but will work across domains too. If you need to store several values, then they can be put into an object and you can store the object's JSON string. E.g. window.name = JSON.stringify(obj)

Possible dijit.Tree Cookie issue (SaveStateCookie)

So our app is set up like the standard left frame with the tree, right frame has the main content (loaded from clicking the tree).
Our web app inconsistently displays a blank page in the main frame in Firefox. By inconsistent I mean everyday for a few, rarely for others, never for most. Once we get this, going to any other page through our tree results in a blank page. We found that deleting the "aTreeSaveStateCookie" restores normal operation. "aTree" is the name of our Div. I found "SaveStateCookie" strings in dijit/Tree.js.
This also happens in IE, except I would get a browser error page which I can't recall right now. I would then delete the only cookie I could find for our app (not sure how to do the Firefox steps in IE)
Any ideas on why this would happen?
Thanks
Dojo 1.3 through http://ajax.googleapis.com/ajax/libs/dojo/1.3/dojo/dojo.xd.js
Firefox 3.1x
IE 8
Windows XP
In my case, I don't recall ever changing browser settings around Private Data.
Please check to see if the response code is 413 (413 = request entity too large), usually this happens when the cookie(s) used to store the tree(s) expansion state (aTreeSaveStateCookie) exceed(s) the maximum request size for your server
You could try increasing the maximum request size (follow instructions for your specific web app server) or at least display a meaningful error message like "please clear your browser cache" when the 413 error code is encountered
If the persist property is set to a truthy value, dijit.Tree is persisting its state to remember which nodes were expanded, and expand them after a page reload. If you need to persist the tree state in presence of a very large data structure, I recommend overriding Tree to use localStorage instead of dojo.cookie.
This is Dojo v. 1.9, but similar changes can be done to the non-AMD version 1.3
_saveExpandedNodes: function(){
if(this.persist && this.cookieName){
var ary = [];
for(var id in this._openedNodes){
ary.push(id);
}
// Was:
// cookie(this.cookieName, ary.join(","), {expires: 365});
localStorage.setItem(this.cookieName, ary.join(","));
}
},
And:
_initState: function(){
// summary:
// Load in which nodes should be opened automatically
this._openedNodes = {};
if(this.persist && this.cookieName){
// Was:
// var oreo = cookie(this.cookieName);
var oreo = localStorage.getItem(this.cookieName);
if(oreo){
array.forEach(oreo.split(','), function(item){
this._openedNodes[item] = true;
}, this);
}
}
},