I am new to automated testing, Protractor, and angularJS. I have a list that I would like to count, copy to an array maybe, and verify the list text is present. For example The list shows Attractions, Capacity, and Content to the user so they know what privileges they have.
Below is the .html
<div class="home-info">
<div class="home-top home-section">
<h3>User Information</h3>
<div class="home-box">
<div class="property-group wide">
<span>
Change Phillips<br />
</span>
</div>
</div>
<div class="home-box">
<div class="property-group wide">
<div>Editors:</div>
<span>
<ul class="property-stack">
<li><span>Attractions</span>
</li>
<li><span>Capacity</span>
</li>
<li><span>Content</span>
</li>
<li><span>Media</span>
</li>
<li><span>Options</span>
</li>
<li></li>
<li></li>
<li><span>Upload CADs</span>
</li>
</ul>
</span>
</div>
</div>
</div>
Below is the code I have written. I can get the first item on the list however using .all isn't working for me.
var text = "";
browser.driver.findElement.all(By.xpath("//li/span")).count().then(function(count) {
initialCount = count;
console.log(initialCount);
});
browser.driver.findElement(By.xpath("//li/span")).getText().then(function(text) {
console.log(text);
});
I'm trying to avoid using xpath as I was told to try and avoid. To be honest Im lost. Thanks for the help in advance.
Code used for matching:
expect(myLists).toEqual(['Attractions', 'Capacity', 'Conent',
'Media', 'Options', 'Upload CADs'
]);
I am not sure what version of protractor you're using but you should be able to just call element without the browser or driver prefix. Using element.all should get you the array of of elements you're looking for.
If you want to access specific indexes within that array you can use the .get(index) suffix to the element.all
So below:
1. you get the array of the elements
2. you get the count of the array
3. we call a for loop to iterate through all the indexes of the array
4. each index of the array we call the getText() and print it to the console
var j = 0; // using this since the i iterator in the for loop doesn't work within a then function
var textList = [];
var text = "";
var myLists = element.all(by.css("li span"));
myLists.count().then(function(count) {
console.log(count);
for(int i = 0; i < count; i++){
myLists.get(i).getText().then(function(text) {
textList[j++] = text;
console.log(text);
});
}
});
EDIT:
In researching I actually found another way to iterate through the array of elements by using the .each() suffix to the element.all.
var j = 0; // using this since the i iterator in the for loop doesn't work within a then function
var textList = [];
var text = "";
var myLists = element.all(by.css("li span"));
myLists.count().then(function(count) {
console.log(count);
myLists.each(function(element, index) {
element.getText().then(function (text) {
textList[j++] = text;
console.log(index, text);
});
});
});
you should be able to use the textList array to match things.
expect(textList).toEqual(['Attractions', 'Capacity', 'Conent',
'Media', 'Options', 'Upload CADs'
]);
Related
I am having an issue with a project I'm working on. I am using an API to return an array of platforms a video game is on. The array is returning the correct results, however I am having trouble displaying those values in my HTML. The result is just showing undefined.
// Renders platform information for each game
const renderPlatformInfo = function (platformResult) {
const gamePlatform = [];
for (let i = 0; i <= `${platformResult.length - 1}`; i++) {
let getPlatforms = gamePlatform.push(platformResult[i].name);
}
gamePlatform.forEach(function (platformItem) {
$('.platforms').append(`<li>${platformItem}</li>`)
});
console.log(gamePlatform);
};
// Renders game information for the searched game
const renderGameInfo = function (gameInfoResult) {
return `<div class="js-game-data row">
<h2 class="game-name col-12">${gameInfoResult.name}</h2>
<img src="${gameInfoResult.image.medium_url}" class="game-image col-4" alt="Box art for ${gameInfoResult.name}">
<ul class="platforms col-6">
<h3 class="col-12">Original release date:</h3>${gameInfoResult.original_release_date}
<h3>Platforms:</h3>
${renderPlatformInfo(gameInfoResult.platforms)}
</ul>
<p class="game-description col-6">${gameInfoResult.deck} <br> <br> <span class="game-details col-12"><b>For more details about the game: Click Here</b></span></p>
</div>
`;
}
renderPlatformInfo can't append children to a DOM element that doesn't exist yet. The UL it's trying to select isn't rendered at the time you're trying to append. Additionally, since renderPlatformInfo doesn't return anything, it will always evaluate to undefined inside a template literal. If you return an HTML string inside renderPlatformInfo, your code should work. Try something like:
let str = '';
gamePlatform.forEach(function(platformItem){
str += `<li>${platformItem}</li>`;
});
return str;
Should renderPlatformInfo return something. Are you missing the return there?
$scope.mainArray = [];
$scope.subArray = [];
var myObject = {}
myObject.task = "write";
myObject.execute = true;
for (var i = 0; i < $scope.mainArray.length; i++) {
$scope.subArray[i] = myObject;
$scope.mainArray[i] = $scope.subArray;
}
How can i show the elements inside my subArray using angular js? I'm using the directive ng-repeat to show my mainArray like: ng-repeat="elements in mainArray"
As per your JS code each element inside your mainArray is basically a subArray. In other words, variable elements from your ng-repeat denotes a subArray. You can iterate over it as shown below and use its value to print content in UI
<div ng-repeat="subArray in mainArray">
<div ng-repeat="item in mainArray">
... do some stuff with item here
</div>
</div>
It would be something like this:
<div ng-repeat="subArray in mainArray">
<div ng-repeat="el in subArray">{{el}}</div>
</div>
Working fiddle
It seems like you have the logic set to make the main array properly
I tried it with getElementById and it worked. But now I want the same with multiple div's so I have to use classes. So I changed the method to getElementsByClassName and now it says undefined.
(The function is called when a option in a select changes. This works correctly)
HTML:
<div class="item_content">
<h3 class="filmnaam">22 jump street</h3>
</div>
<div class="item_content">
<h3 class="filmnaam">rio 2</h3>
</div>
Javascript:
function sorting(sortingway) {
alert(sortingway.value);
var titelfilms = document.getElementsByClassName("filmnaam");
var titels = titelfilms.innerHTML;
console.log(titels[0]);
}
Is there a way to do this without jQuery?
getElementsByClassName returns a collection, so loop that!
var titelfilms = document.getElementsByClassName("filmnaam");
for (var i = 0; i < titelfilms.length; i++) {
var titels = titelfilms[i].innerHTML;
console.log(titels);
}
titelfilms is a node list, you can't get the innerHTML of a node list as a whole, it contains multiple references to elements which each have their own individual property.
You could loop through and concatenate each innerHTML onto a variable, or you could map() the innerHTML of your returned elements to an array and then join() them up:
function sorting(sortingway) {
var titelfilms = document.getElementsByClassName("filmnaam");
var titels = Array.prototype.map.call(titelfilms, function (el) {
return el.innerHTML;
}).join(' ');
console.log(titels);
}
sorting();
<div class="item_content">
<h3 class="filmnaam">22 jump street</h3>
</div>
<div class="item_content">
<h3 class="filmnaam">rio 2</h3>
</div>
So i have a html layout in which there are blocks (there are no fix number of them, because they can be created dynamically).
In these blocks there are boxes (again, they can be created dynamically)
The boxes contain *html element*s and also have different data attributes
So i need to create an object which looks like this
block1 = {
box1 : {
id : box1.data('id'),
content : box1.html()
},
box2 : {
id : box2.data('id'),
content : box2.html()
}
},
block2 = {
box3 : {
id : box3.data('id'),
content : box3.html()
}
}
Please don't write that the syntax is not correct, i know. I just tried to somehow illustrate what i want.
So my question is how do i do this with the help of jQuery?
Thank you in advanced
You can select all blocks and boxes and iterate over each of them using .each [docs]:
var blocks = {};
$('.block').each(function(index) {
var boxes = {};
$(this).find('.box').each(function(index) {
boxes['box' + index] = {
id: $(this).data('id');
content: $(this).html();
};
});
blocks['block' + index] = boxes;
});
You might not need an object of objects though, maybe an array of array suffices or would be even better, depending on what you intend to do with the data.
To learn more about how objects work, have a look at MDN - Working with Object.
Here is an idea:
1- Iterate over all of the blocks using some CSS selector.
2- Create a generic JS object and set a collection attribute called "boxes" to be an array
3- For each one, iterate over all the boxes inside it, again, using some CSS selector.
4- Create a generic JS object for each box and set the attributes as needed.
Code version
I think something like this would work (not tested):
var blocks = new Array();
$(".blocks").each(function(b) {
var my_block = {boxes: new Array()};
var $block = $(b);
$(".box", $block).each(function(box) {
var $box = $(box);
my_block.boxes.push({id: $box.attr("id"), content: $box.html()});
});
blocks.push(my_block);
});
You should take a look at Knockout.js, it's very comfortable to build an application like yours.
In detail: use Objects. Build an array for yourself, containing Objects with e.g. Block Name and all Child nodes.
<div id="lanesContainer" data-bind="foreach: blocks">
<div id="" class="dropLane laneDefault ui-widget-header ui-dialog ui-widget ui-corner-all ui-front ui-resizable">
<div class="ui-dialog-titlebar ui-helper-clearfix" data-bind="drop: {value: $data.dropTask}">
<p class="laneheader" data-bind="text: $data.title">Lane</p>
</div>
<ul data-bind="foreach: box">
<li class="ui-dialog-content laneItem" data-bind="drag: {value: $data}">
<div class="ui-widget-header laneItemHeader" data-bind="text: $data.Title"></div>
<div class="ui-widget-content laneItemBody" data-bind="text: $data.Description"></div>
<div class="ui-widget-content laneItemFooter">
<div class="ui-corner-all ui-state-default notification-important">
<span class="ui-icon ui-icon-notice" title="sometitle" data-bind="css: {'notification-important-hide': !$root.isElementImportant($data) }"></span>
</div>
</div>
</li>
</ul>
</div>
</div>
Is this useful?
Here is how to get an Object with nested Array of Childs:
function laneObject(title) {
var obj = new Object();
obj.title = title; //Identifier for Lane
obj.childs = []; //Elements of Lane to display
return obj;
}
I am not entirely sure of what your question is, but if you want to create blocks and boxes dynamically, I suggest you first of all use Arrays.
//All dynamically created blocks
blocks = [];
//Create blocks
for(var i = 1; i < 3; i++) {
var block = {
//All dynamically generated bloxes
boxes = [];
};
//Create boxes
for(var j = 1; j < 4; j++) {
block.box[j] = {
id : j,
content : '<span>html for box' + j + '</span>'
}
}
blocks[i] = block;
}
I was wondering how I would go about finding and replacing some text in a div, but i want to find and replace the second occurrence of that text. For example:"You just added a item, please remove this item" so I would like to find the second "item" and replace it with whatever text I choose.
JS:
var compareCount = $('.compareWidget').find('.compareItem').length;
if (compareCount >= 2) {
$('.message').find('.count').text(compareCount);
$('message').html().replace('item', 'items');
}
$('.message').slideDown("Fast");
setTimeout(function () {
$('.message').slideUp("Fast");
}, 5000);
HTML:
<div id="alertMessage">
<div class="message">
<span>You just added a item to compare, you currently have <span class="count">1</span> item to compare</span>
</div>
</div>
"you currently have 1 item to compare"
You want to turn item to items?
You can do it with regular expressions, or you can wrap it into an element and grab that.
<span class="count">1</span> <span class="type">item</span> to compare</span>
and
$('.message').find('.type').text("items");
Using regular expressions you can
function replaceMatch(originalString, searchFor , replaceWith, matchNumber)
{
var match = 0;
return originalString.replace(searchFor, function(found){
match++;
return (match===matchNumber)?replaceWith:found;
},'g');
}
and call it like
var msg = $('.message');
msg.html( replaceMatch( msg.html(), 'item', 'items', 2) );
demo http://jsfiddle.net/gaby/crhvA/