Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save roycollings/4351328 to your computer and use it in GitHub Desktop.
Save roycollings/4351328 to your computer and use it in GitHub Desktop.
Javascript: get all object elements and values into a simple array.
//
// Example object.
//
var DOM_matchers = {
pageURL : "/startPage",
emailBox : {model:"emailAddress", selector:"#emailAddress"},
passwordBox: {model:"password" , selector:"#password"},
enterBTN : {selector:".enterBTN"}
};
//
// JS to get an array of these items (so they can easily be checked against the current DOM for example).
//
function createArray(p_obj) {
// Get every value in the object into a simple array ...
var thisObj_items = [];
var thisYes = false;
for (var key in eval(p_obj)) {
thisYes = false;
if (eval(p_obj).hasOwnProperty(key)) {
var obj = eval(p_obj)[key];
for (var prop in obj) {
// Can't find a better way to do this, but if I assume anything
// with child object which is just numeric is NOT a parent.
// Otherwise you get things like:
// PageURL.1 = "/",
// PageURL.2 = "s",
// PageURL.3 = "t" ... etc...
var myregex = /^[0-9]*$/;
if (myregex.exec(prop) != prop) {
thisYes = true;
thisObj_items.push({item:key + "." + prop, type:prop, value:obj[prop]});
}
}
if ( ! thisYes )
thisObj_items.push({item:key, type:key, value:obj});
}
}
};
var myObjArray = createArray(DOM_matchers);
//
// Now myObjArray contains this:
//
// myObjArray[0] .item = "pageURL" , .type = "pageURL" , .value = "/startPage"
// myObjArray[1] .item = "emailBox.model" , .type = "model" , .value = "emailAddress"
// myObjArray[1] .item = "emailBox.selector" , .type = "selector", .value = "#emailAddress"
// myObjArray[2] .item = "passwordBox.model" , .type = "model" , .value = "password"
// myObjArray[2] .item = "passwordBox.selector", .type = "selector", .value = "#password"
// myObjArray[3] .item = "enterBTN.selector" , .type = "selector", .value = ".enterBTN"
//
// So we can do things like this (using AngularJS E2E in this example):
//
decsribe('DOM check', function() {
$.each(myObjArray, function(idx, X) {
switch(X.type) {
case "model":
it(X.item + ' is an input field on this page', function() {
expect(input(X.value).val()).toBeDefined();
});
break;
case "selector":
it(X.item + ' is an element on this page', function() {
expect(element(X.value).val()).toBeDefined();
});
break;
case "pageURL":
it(X.item + ' is the url of this page', function() {
expect(browser().location().url()).toBe(X.value);
});
break;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment