nightwatch - still can't switch to the other window - selenium

The example from github doesn't work for me.
https://github.com/nightwatchjs/nightwatch/issues/369
This is my code.
When('I open a new browser window', () => {
var host = 'http://www.google.com';
client
.windowHandle(function(wh){console.log(wh.value)})
.url(host)
.waitForElementVisible('#hplogo', 1000)
.execute(function(newWindow){
window.open('http://www.twitter.com', null, "height=1024,width=768");
}, [host])
.assert.urlContains('google')
.window_handles(function(result) {
var temp = result.value[1];
this.switchWindow(temp);
})
.windowHandle(function(wh){console.log(wh.value)})
.assert.urlContains('twitter')
.end();
});
Both console.log before and after .switchWindow print out the same string.
Does anyone have any ideas please...?
EDIT
I've changed the code a bit taking into account what pcalkins said.
This is the code now:
When('I open a new browser window', () => {
var host = 'http://www.google.com';
client
.windowHandle(function(wh){console.log("\nBEFORE: " + wh.value)})
.url(host)
.waitForElementVisible('#hplogo', 1000)
.execute(function(newWindow){
window.open('http://www.twitter.com', null, "height=1024,width=768");
}, [host])
.pause(3000)
.window_handles(function(result) {
console.log("\n\nHANDLE: " + result.value + "\n");
var temp = result.value[0];
this.switchWindow(temp);
console.log("\n\ntemp0: " + temp + "\n");
temp = result.value[1];
this.switchWindow(temp);
console.log("\n\ntemp1: " + temp + "\n");
})
.pause(2000);
});
When run, this is the result:
BEFORE is the handle for the original window.
HANDLE is both windows.
temp0 and temp1 are the two different windows in sequence. Clearly temp1 is the window I want, and yet the final this.switchWindow is not doing its job.
AFTER is the current window handle at the next test step.

Related

Postman. How can I use assertion / expect and console log together?

pm.test('Check if employee filled their skills', function() {
jsonData.forEach(function(item) {
expect(item.MainEmployeeSkills).to.be.not.empty;
if (item.MainEmployeeSkills.length < 1) {
console.log(item.fullName + " doesn't have skills");
}
})
})
After expect code is unreachable. But I want to know that test failed and log results.
Please, help
var jsonData = [2, 2, 3, 2, 2]
jsonData.forEach(function (a) {
pm.test("Your test name", function () {
if (item.MainEmployeeSkills.length < 1) {
console.log(item.fullName + " doesn't have skills");
}
pm.expect(a).to.eql(2);
});
})
you should print it before the pm.expect as it throws an exception and nexyt line won't be executed.
Also there is no point of having for loop inside pm.text as the loop exists for the first except itself ( unless this is what you want )
If you are looking way to print descriptive assertion message yu don't havr to do this. Instead use:
pm.test('Check if employee filled their skills', function() {
jsonData.forEach(function(item) {
pm.expect(item.MainEmployeeSkills,item.fullName + " doesn't have skills").to.be.not.empty;
})
})

Node-Webkit Ctrl-plus and Ctrl-minus

How do i make node-webkit (NW) accept Ctrl++ and Ctrl+- as shortcuts?
I have tried:
Ctrl++
Ctrl+Plus
Ctrl+Plus
Ctrl+Minus
Ctrl+-
Ctrl+minus
but it doesn't work. Every time it gives me a fail message.
Here is my current code:
var option = {
key : "Ctrl+plus",
active : function() {
console.log("Global desktop keyboard shortcut: " + this.key + " active.");
},
failed : function(msg) {
console.log(msg);
}
};enter code here
var shortcut = new nw.Shortcut(option);
nw.App.registerGlobalHotKey(shortcut);
I had to do something similar and ended up using JS:
$(window).keypress(function(event) {
if (!(event.which == 61)) return true;
# 61 is ctrl + plus on Mac, probably different on windows
alert("Ctrl-plus pressed");
event.preventDefault();
return false;
});

PhantomJS crashes after 150-180 urls

My script works fine so far, loading every page in the text file line by line in sequentiell order (page.open is asynchron and the page object is global = overwriting on new requests, it's a big clusterfuck running multiple page.open() at once), matching every request for a specific domain and printing JSON values from it.
But if I use a .txt-file with over ~150 links, it just crashes every time, mostly with no error message and with no crash dump like this:
PhantomJS has crashed. Please read the crash reporting guide at
http://phantomjs.org/crash-reporting.html and file a bug report at
https://github.com/ariya/phantomjs/issues/new.
Unfortunately, no crash dump is available.
(Is %TEMP% (C:\Users\XXX\AppData\Local\Temp) a directory you cannot write?)
I can reproduce that easily if I run it multiple times, doesn't matter if I do it at once or one after one.
How can I prevent the crashes? My script is useless if Phantom can't handle that.
But sometimes I get a crash dump:
PhantomJS has crashed. Please read the crash reporting guide at
http://phantomjs.org/crash-reporting.html and file a bug report at
https://github.com/ariya/phantomjs/issues/new.
Please attach the crash dump file:
C:\Users\XXX\AppData\Local\Temp\a4fd6af6-1244-44d3-8938-3aabe298c2fa.dmp
https://www.dropbox.com/s/i3qi5ed33mbblie/500%20links%20-a4fd6af6-1244-44d3-8938-3aabe298c2fa.dmp?dl=1
https://www.dropbox.com/s/najdz9fhdexvav1/500%20links-%2095ebab5c-859b-40e9-936b-84967471779b.dmp?dl=1
https://www.dropbox.com/s/1d2t8rtev85yf96/500%20links%20-%20d450c8e1-9728-41c7-ba52-dfef466f0222.dmp?dl=1
And in rare cases I even get an error message, Process Explorer says the process has a maximum of 21 threads at once
QThread::start: Failed to create thread ()
console.log('Hello, world!');
var fs = require('fs');
var stream = fs.open('500sitemap.txt', 'r');
var webPage = require('webpage');
var i = 1;
var hasFound = Array();
var hasonLoadFinished = Array();
function handle_page(line) {
var page = webPage.create();
page.settings.loadImages = false;
page.open(line, function() {});
page.onResourceRequested = function(requestData, request) {
var match = requestData.url.match(/example.de\/ac/g)
if (match != null) {
hasFound[line] = true;
var targetString = decodeURI(JSON.stringify(requestData.url));
var klammerauf = targetString.indexOf("{");
var jsonobjekt = targetString.substr(klammerauf, (targetString.indexOf("}") - klammerauf) + 1);
targetJSON = (decodeURIComponent(jsonobjekt));
var t = JSON.parse(targetJSON);
console.log(i + " " + t + " " + t['id']);
request.abort;
} else {
//hasFound = false;
return;
}
};
page.onLoadFinished = function(status) {
if (!hasonLoadFinished[line]) {
hasonLoadFinished[line] = true;
if (!hasFound[line]) {
console.log(i + " :NOT FOUND: " + line);
console.log("");
}
i++;
setTimeout(page.close, 200);
nextPage();
}
}
};
function nextPage() {
var line = stream.readLine();
if (!line) {
end = Date.now();
console.log("");
console.log(((end - start) / 1000) + " Sekunden");
phantom.exit(0);
}
hasFound[line] = false;
hasonLoadFinished[line] = false;
handle_page(line);
}
start = Date.now();
nextPage();
/edit crashed with 1.9.8 after 3836 links .... back to start ...........
Seems like the problem lies into the 2.0 version. Tested 1.9.8 out of frustration and - it works, 60% less RAM used, no crashes with 1000 Urls.
Crash report on github is done, what a relief, it works.

How to use eval on jquery plugin variable?

I'm using pnotify, the JQuery plugin.
I want to shorten this code:
$.pnotify.defaults.styling = "jqueryui";
$.pnotify.defaults.delay = 1500;
$.pnotify.defaults.title = 'Error'
$.pnotify.defaults.mouse_reset = false;
$.pnotify.defaults.history = false;
Into something like this:
var darray = { 'styling':'\'jqueryui\'', 'delay':'1500', 'title':'\'Error\'', 'mouse_reset':'false', 'history':'false' };
$.each(darray, function(option,choice){
eval("var $.pnotify.defaults." + option + "=" + choice + ";");
});
However, despite trying all sorts of things, I have failed. Here's some of the things I've tried:
var darray = { 'styling':'\'jqueryui\'', 'delay':'1500', 'title':'\'Error\'', 'mouse_reset':'false', 'history':'false' };
$.each(darray, function(option,choice){
eval("var $.pnotify.defaults." + option + "=" + choice + ";");
});
JSONstring='var $.pnotify.defaults.' + option + "=" + choice + ";";
$.parseJSON(JSONstring);
string99 = 'var $\.pnotify\.defaults\.' + option
$.parseJSON('{string99=choice}');
option='var $.pnotify.defaults.'+option;
var JSONObject= {'option':choice};
$.parseJSON(JSONObject);
Fiddle: http://jsfiddle.net/morossive/kayKn/
You could try this (untested, but you get the idea):
var darray = {
styling: 'jqueryui',
delay: 1500,
title: 'Error',
mouse_reset: false,
history: false
};
for (var mbr in darray) {
$.pnotify.defaults[mbr] = darray[mbr];
}
Because JavaScript treats objects like hashtables, we can iterate over their "keys" (for (var mbr in darray)) and assign new values to new keys in objects. For example:
var obj = {...};
// The following are equivalent:
obj.x = 5;
obj['x'] = 5;
However, I think there may be an even more elegant solution to your problem (don't use this if you are worried about overwriting preexisting values in $.pnotify.defaults, however):
$.pnotify.defaults = {
styling: 'jqueryui',
delay: 1500,
title: 'Error',
mouse_reset: false,
history: false
};
I know you asked how to use eval to solve this, but I think in general any alternative to using eval is probably better.

How can I Recursively Read Files and Folders using JavaScript

I've just started discovering Windows StoreApps (that's what Microsoft calls it) and I'm following the sample code here about using the FolderPicker.
I want to Iterate through the folder and read all the sub-folders and files.
There are two functions I've looked at which I thought are what I need but I'm not able to do it properly after trying hours.
In the link above, the line which says:
WinJS.log && WinJS.log("Picked folder: " + folder.name, "sample", "status");
I tried to dig deeper in the folder with something like:
folder.getFoldersAsync().then(function (folderItem) {
document.getElementById('musicFolder').innerHTML += folderItem.length + " folders)<br/>";
folderItem.forEach(function (x) {
document.getElementById('musicFolder').innerHTML += "--" + x.name + "<br/>";
x.getFilesAsync().then(function (items) {
document.getElementById('musicFolder').innerHTML += items.length + " files"+"<br>";
});
});
});
UPDATE:
I have been struggling but can't get the stuff organized while iterating folders and sub-folders.
#Damir's code doesn't dig deepest folder. We need a recursive function. I could come up with the following function but as I said result is not organized
function scanFolder(folder) {
var isInc = false;
folder.getFoldersAsync().then(function (folderItem) {
if (folderItem.length > 0) {
folderItem.forEach(function (x) {
if (!isInc) {
isInc = true;
hyphen += "-";
}
document.getElementById('musicFolder').innerHTML += hyphen + x.name + "</br>";
x.getFilesAsync().then(function (items) {
items.forEach(function (item) {
allTracks.push({
name: item.name,
path: item.path
});
document.getElementById('musicFolder').innerHTML += hyphen +"-"+ item.name + "</br>";
});
}).done(function () {
scanFolder(x);
});
});
}
});
}
You want to read all the subfolders and the files inside them? Something like this should work:
folder.getFoldersAsync().then(function (folderItem) {
document.getElementById('musicFolder').innerHTML += "(" + folderItem.length + " folders)<br/>";
folderItem.forEach(function (x) {
x.getFilesAsync().then(function (items) {
document.getElementById('musicFolder').innerHTML += "--" + x.name + " (" + items.length + " files)<br>";
items.forEach(function(item) {
document.getElementById('musicFolder').innerHTML += "----" + item.name + "<br>";
});
});
});
});
EDIT:
There's actually no need for recursion to recursively scan a folder and its subfolders in WinRT. You can use StorageFolder.CreateFileQueryWithOptions() instead:
var options = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.defaultQuery, ['*']);
options.folderDepth = Windows.Storage.Search.FolderDepth.deep;
folder.createFileQueryWithOptions(options).getFilesAsync().then(function (files) {
var paths = new Array();
files.forEach(function(file) {
paths.push(file.path);
});
paths.sort();
paths.forEach(function(path) {
document.getElementById('musicFolder').innerHTML += path + "<br>";
});
});
From here on you can transform the flat list of files to whatever you need instead of just printing out their path.