Find an Element in Protractor - protractor

<div>
<label localize="{data: 'Name', suffix: ':'}">Name:</label>
<span class="required" ng-class="{'disabled': meterCreating}" input-control="{title: 'Meter', okCallback:setMeterName, value: meter.meterName, ss: 'meters'}">
<span hs-placeholder="Enter Name" class="ng-binding"></span>
</span>
</div>
What is the best way to find an element: placeholder = "Enter Name"?
Scenario: find an element using Snippet above
User clicks on the "Enter Name" box, another windows pops-up for entering a name.

Based off that HTML, the cleanest way I can see is by css chaining:
element(by.css('span.required span.ng-binding')) (would normally just be span.ng-binding, but I highly doubt that's unique. I also doubt that span.required span.ng-binding is unique either)
There are many other options, however they won't be pretty cause they will be similar chains.
element(by.cssContainingText('label', 'Name:')).element(by.css('span > span'));
or
element(by.css('div label span.ng-binding')) etc..
I would suggest asking your developers for better locators (specifically, ID's), it makes JavaScript way easier. Unfortunately, I don't think you're able to locate that element by HTML attributes, which is one of my favorite ways. It would have looked like this:
element(by.css('span[placeholder=Enter Name]')) -- but I'm pretty sure that will throw an error for invalid locator. It accepts most "standard" html attributes such as value, option, style etc...

Related

Locators combination

I am working on protractor to test the AngularJs application. Here I came across one scenario where I want to click on image for different users. But the id for image is same for all (say 10) users. So I found one more element that is one unique number allocated to each user. The code for 2 different users are:
USER1:
img id="searchPatientImgAdmittedM" class="img-circle picwidth" ng-click="getPatientVitalLabPharmacy(patient.patientId._id)" onclick="ShowHide(this)" src="icons/male.png" alt="" role="button" tabindex="0"
span class="clearfloat ng-binding">12339/span
USER2:
img id="searchPatientImgAdmittedM" class="img-circle picwidth" ng-click="getPatientVitalLabPharmacy(patient.patientId._id)" onclick="ShowHide(this)" src="icons/male.png" alt="" role="button" tabindex="0"
span class="clearfloat ng-binding">8841/span
EDIT:
The full HTML code
<div class="col-md-10 col-sm-9 col-xs-9 skin-font-color paddingTop7">
<span class="skin-font-color">
<span class="name clearfloat ng-binding">KRISHA</span>
<span class="clearfloat ng-binding">12348</span>
<img id="searchPatientImgAdmittedF" class="img-circle picwidth" ng-click="getPatientVitalLabPharmacy(patient.patientId._id)" onclick="ShowHide(this)" src="icons/femaleImages.jpg" alt="" role="button" tabindex="0">
</div>
I tried to do :
element(by.id('searchPatientImgAdmittedF')).all(by.tagName('‌​12348')).click();
// or
element(by.id('searchPatientImgAdmittedF')).element(by.tagNa‌​me('12348')).click()‌​;
How can I make combination of locators to click on this users. Only image part is clickable.
Thanks four your additions.
Now you're trying to click on a sister-element. There are several approaches to do so.
The one I'm usually using is:
element(by.cssContainingText('span.clearfloat','12348')).element(by.xpath('..')).$('#searchPatientImgAdmittedF').click();
//equal to
element(by.cssContainingText('span.clearfloat','12348')).element(by.xpath('..')).element(by.id('searchPatientImgAdmittedF')).click();
This evaluates first the identifiable tag with the unique number, then climbs up to its parent element, then from there gets the img-element with the ID.
The $() selector
The cssContainingText() selector
Another option would be to use isElementPresent(), which evaluates the existence of a child-element. However, the code is (from my point of view) more complex and I don't see, how cssContainingText() could be used there, so I don't try to do it here.
Thanks for your quick help in solving my issue. I want to add here that I found the answer to my problem and now I am able to click on the particular user I want from the list of many users. The code I am using is :
element(by.cssContainingText('span.clearfloat','12339'))
.element(by.xpath('/html/body/div[3]/div[1]/div[17]/div/div/table[4]/tbody/tr[3]/td[1]/div[1]/img'))
.click();
This is finding the child element first and then the parent element.The id was all same for all the users so it was not taking that and so I used only xpath along with unique number.
Thanks again for the help.

Why does the first assert work, but not the second?

I'm using Watir WebDriver with Firefox.
Here are two asserts for the same element. The first works, but not the second:
assert_match(/Please add user to GMT/, #browser.small(:class, "error").text)
assert_match(/Please add user to GMT/, #browser.div(:class, "eight mobile-three columns").small(:class, "error").text)
I need the second assert to work, because there are 8 error messages on the page, which are presented if the user does not populate 8 mandatory fields. All 8 errors have the identical HTML. So, I need to be able to step down from the parent.
Here is the HTML:
<div class="eight mobile-three columns">
<a id="btnAddUserToGMT" class="success radius button expand error" onclick="AddUserToGMT();" data-reveal-id="addToGMT" href="#"> … </a>
<small class="error" style="margin-top:0px;">
Please add user to GMT
</small>
</div>
Here is the error message:
Watir::Exception::UnknownObjectException: unable to locate element, using {:class=>"error", :tag_name=>"small"}
C:/Ruby193/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.4/lib/watir-webdriver/elements/element.rb:490:in `assert_exists'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/watir-webdriver-0.6.4/lib/watir-webdriver/elements/element.rb:85:in `text'
C:/Documents and Settings/Asserts_01.rb:22:in `testBasic'
The complaint for the second assert is:
unable to locate element, using {:class=>"error", :tag_name=>"small"}
And yet that same using was OK for the first assert.
Problem solved.
After discussion with the developer, it appears that by some unusual manipulation of automatically generated HTML, the text of the error message appears at its correct location on the page. But the assertion must be based on a different tag, which is specified at some completely different position on the page.
For example, I was trying to assert on this code at the correct position:
<small class="error" style="margin-top:0px;">
Gender is required
</small
Even unique xPath generated by FirePath failed to find this.
What I should have asserted on was a HIDDEN tag on a completely different part of the page.
<input id="errorMsgGenderID" name="errorMsgGenderID" type="hidden" value="Gender is required" />
There were several such tags for each mandatory field that was not populated, all bunched together on the same line. They were all "input" tags, which puzzled me.

Autofill input type="text" field from an external link

I have a link on one page which looks like this:
http://www.domain.com/sample-link#product_id
and on the other page (sample-link), I have this input field:
<input type="text" name="name" value="name" />
So, when I click the link from the first page, I want to open the "sample-link" page, and autofill the name field with the "product_id" text. Any ideas how can I make this?
Thanks in advance.
You'll just have to add a tiny Javascript snippet:
if (document.location.hash)
document.getElementById('testbox').value = decodeURIComponent(document.location.hash.substr(1));
For obvious reasons you'll have to adjust the id of the text box.
It gets a bit more complicated in case you'd like to pass more than one value.
The call to decodeURIComponent() is optional, but required in case you're passing characters like spaces or non-alphanumerical stuff (just to be sure).

ASP.NET MVC 2 and lists as Hidden values?

Hi,
I have a View class that contains a list, this list explains the available files that the user have uploaded (rendered with an html helper).
To maintain this data on submit I have added the following to the view :
<%: Html.HiddenFor(model => model.ModelView.Files)%>
I was hoping that the mode.ModelView.Files list would be returned to the action on submit but it is not?
Is it not possible to have a list as hiddenfield?
More information : The user submit a couple of files that is saved on the service, when saved thay are refered to as GUID and is this list that is sent back to the user to render the saved images. The user makes some changes in the form and hit submit again the image list will be empty when getting to the control action, why?
BestRegards
Is it not possible to have a list as hiddenfield?
Of course that it is not possible. A hidden field takes only a single string value:
<input type="hidden" id="foo" name="foo" value="foo bar" />
So if you need a list you need multiple hidden fields, for each item of the list. And if those items are complex objects you need a hidden field for each property of each item of the list.
Or a much simpler solution is for this hidden field to represent some unique identifier:
<input type="hidden" id="filesId" name="filesId" value="123" />
and in your controller action you would use this unique identifier to refetch your collection from wherever you initially got it.
Yet another possibility is to persist your model into the Session (just mentioning the Session for the completeness of my answer sake, but it's not something that I would actually recommend using).
Before I start I'd just like to mention that this is an example of one of the proposed solutions that was marked as the answer. Darrin got it right, here's an example of an implementation of the suggested solution...
I had a similar problem where I needed to store a generic list of type int in a hiddenfield. I tried the standard apporach which would be:
<%: Html.HiddenFor(foo => foo.ListOfIntegers) %>
That would however cause and exception. So I tried Darrin's suggestion and replaced the code above with this:
<%
foreach(int fooInt in Model.ListOfIntegers)
{ %>
<%: Html.Hidden("ListOfIntegers", fooInt) %>
<% } %>
This worked like a charm for me. Thanks Darrin.

jQuery ajaxSubmit(): ho to send the form referencing on the fields id, instead of the fields name?

im pretty new to jQuery, and i dont know how to do that, and if it can be done without editing manually the plugin.
Assume to have a simply form like that:
<form action="page.php" method="post">
Name: <input type="text" name="Your name" id="contact-name" value="" />
Email: <input type="text" name="Your email" id="contact-email" value="" />
</form>
When you submit it, both in 'standard' way or with ajaxSubmit(), the values of the request take the label of the field name, so in the page.php i'll have:
$_POST['Your name'];
$_POST['Your email'];
Instead i'll like to label the submitted values with the id of the field:
$_POST['contact-name'];
$_POST['contact-email'];
Is there a way to do that with jquery and the ajaxsubmit() plugin?
And, maybe, there is a way to do it even with the normal usage of a form?
p.s: yes, i know, i could set the name and id attributes of the field both as 'contact-name', but how does two attributes that contain the same value be usefull?
According to the HTML spec, the browser should submit the name attribute, which does not need to be unique across elements.
Some server-side languages, such as Rails and PHP, take multiple elements with certain identical names and serialize them into data structures. For instance:
<input type="text" name="address[]" />
<input type="text" name="address[]" />
If the user types in 1 Infinite Loop in the first box and Suite 45 in the second box, PHP and Rails will show ["1 Infinite Loop", "Suite 45"] as the contents of the address parameter.
This is all related to the name attribute. On the other hand, the id attribute is designed to uniquely represent an element on the page. It can be referenced using CSS using #myId and in raw JavaScript using document.getElementById. Because it is unique, looking it up in JavaScript is very fast. In practice, you would use jQuery or another library, which would hide these details from you.
It is reasonably common for people to use the same attribute value for id and name, but the only one you need to care about for form submission is name. The jQuery Form Plugin emulates browser behavior extremely closely, so the same would apply to ajaxSubmit.
It's the way forms work in HTML.
Besides, Id's won't work for checkboxes and radio buttons, because you'll probably have several controls with the same name (but a different value), while an HTML element's id attribute has to be unique in your document.
If you really wanted, you could create a preprocessor javascript function that sets every form element's name to the id value, but that wouldn't be very smart IMHO.
var name = $("#contact-name").val();
var email = $("#contact-email").val();
$.post("page.php", { contact-name: name, contact-email: email } );
This will let you post the form with custom attributes.