NoSuchElementException - junit test error - java

I am using selenium junit testing.
If i try with selenium ide, the test goes well, but with junit it gives me this error:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#firstName"}
I think that the span doesn't redirect to the page it should (but in normal schedule it does).
#Test
public void adminCreateDoc() {
driver.get("http://localhost:8080/login");
driver.manage().window().setSize(new Dimension(550, 706));
driver.findElement(By.linkText("Accesso amministratori")).click();
driver.findElement(By.id("username")).sendKeys("8245");
driver.findElement(By.id("password")).click();
driver.findElement(By.id("password")).sendKeys("prova1");
driver.findElement(By.cssSelector(".btn")).click();
driver.findElement(By.id("btn_createDoc")).click();
driver.findElement(By.id("firstName")).click();
driver.findElement(By.id("firstName")).sendKeys("Marco");
driver.findElement(By.id("lastName")).click();
driver.findElement(By.id("lastName")).sendKeys("Battiato");
driver.findElement(By.id("doc_type")).click();
driver.findElement(By.id("doc_type")).sendKeys("Cardiologo");
driver.findElement(By.id("id")).click();
driver.findElement(By.id("id")).sendKeys("855555");
driver.findElement(By.id("password")).click();
driver.findElement(By.id("password")).sendKeys("prova1");
driver.findElement(By.cssSelector(".glyphicon-send")).click();
}
I've tried with xpath, but without success...
HTML page with span redirection:
<body>
<div class="container text-center">
<div align="center">
<h2>Gestione dottori</h2>
<table class="table table-striped table-responsive-md">
<tr>
<th>ID</th>
<th>Nome</th>
<th>Specialit&agrave</th>
</tr>
<tr th:each="doc: ${listDoc}">
<td th:text="${doc.getId()}"></td>
<td>Dr. <span th:text="${doc.getFirstName()}"></span> <span th:text="${doc.getLastName()}"></span></td>
<td th:text="${doc.getDoc_type()}"></td>
</tr>
</table>
<a th:href = "#{/admin_createdoc}"><span id="btn_createDoc" class="plus bg-dark" >+</span></a>
<hr>
<div class="col col-lg-2 align-self-center">
<div class="p-1">
<form th:action="#{/admin_logout}" method=post>
<button name="btn_logout_profile" id="btn_logout_profile"
type="submit" class="btn btn-primary">Log Out</button>
</form>
</div>
</div>
</div>
</div>
</body>
Which redirect to this page:
<body>
<div class="container">
<div class="d-flex align-items-center justify-content-start">
<form th:action="#{/admin_homepage}" method=get>
<button name="btn_back_profile" id="btn_back_profile" type="submit"
class="btn btn-info">
<span class="fas fa-chevron-left"></span>
</button>
</form>
</div>
<br>
<div style='text-align: center'>
<form class="well form-horizontal" action="#"
th:action="#{/saveDoctor}" th:object="${doc}" method="POST"
id="contact_form">
<fieldset>
<!-- Form Name -->
<legend>
<center>
<h2>
<b>Doctor Creation Form</b>
</h2>
</center>
</legend>
<br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">First Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input name="first_name"
th:field="*{firstName}" placeholder="Doc First Name"
class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Last Name</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input name="last_name"
th:field="*{lastName}" placeholder="Doc Last Name"
class="form-control" type="text" required>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Type</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-list"></i></span> <input name="doc_type"
th:field="*{doc_type}" placeholder="Doc Type"
class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Id</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input name="id"
th:field="*{id}" placeholder="Doc ID" class="form-control"
type="number" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i
class="glyphicon glyphicon-user"></i></span> <input
th:field="*{password}" name="doc_password"
placeholder="Doc Password" class="form-control" type="password"
required>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group" align="center">
<label class="col-md-4 control-label"></label>
<div class="col-md-4">
<br>
<button type="submit" class="btn btn-warning">
SUBMIT <span class="glyphicon glyphicon-send"></span>
</button>
</div>
</div>
</fieldset>
</form>
<div>
<form th:action="#{/admin_logout}" method=post>
<button name="btn_logout_profile" id="btn_logout_profile"
type="submit" class="btn btn-primary">Log Out</button>
</form>
</div>
</div>
</div>
</body>
Thank you for your time!

The failure is happening on this line
driver.findElement(By.id("firstName")).click();
ID as a CSS selector is #firstName. Since this is right after a page transition, my guess is that the page isn't fully loaded before the next line of code is run. This can sometimes happen on a modern site where the page is loaded but there's still stuff being loaded asynchronously in the background. The fix is to add a wait, specifically a WebDriverWait, to the following line. That is one option...
Instead of adding a wait piecemeal when it's found that you need it, I prefer to write helper methods that take care of common actions like click(), sendKeys(), etc. and then let those methods take care of the specific waits for me.
public void click(By locator) {
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(locator)).click();
}
public void sendKeys(By locator, String text) {
findElement(locator).sendKeys(text);
}
public WebElement findElement(By locator) {
return new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(locator));
}
Then you can change your script to
#Test
public void adminCreateDoc() {
driver.get("http://localhost:8080/login");
driver.manage().window().setSize(new Dimension(550, 706));
click(By.linkText("Accesso amministratori"));
sendKeys(By.id("username"), "8245");
sendKeys(By.id("password"), "prova1");
click(By.cssSelector(".btn"));
click(By.id("btn_createDoc"));
sendKeys(By.id("firstName"), "Marco");
sendKeys(By.id("lastName"), "Battiato");
sendKeys(By.id("doc_type"), "Cardiologo");
sendKeys(By.id("id"), "855555");
sendKeys(By.id("password"), "prova1");
click(By.cssSelector(".glyphicon-send"));
}
which I think makes it more readable, adds waits to everything in case it's needed with no extra code, and so on...
The next level is using the Page Object Model to contain the locators and methods for each page. Then your code gets cleaned up significantly, makes it near-human readable, and MUCH easier to manage.

Related

Why invalid-feedback in thymeleaf not working

I required input it's work but why invalid-feedback not show in modal
HTML use thymeleaf
<!-- AddStore Modal -->
<div class="modal fade" id="AddUserModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AddUserModalLabel">Add Store Form</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form autocomplete="off" action="#" th:action="#{/stores/add_store}"
th:object="${store}" method="post"
role="form" id="addModalForm">
<div class="form-row">
<div class="form-group col-md-6">
<label for="addstoreName">Store Name</label>
<input type="text" class="form-control" id="addstoreName" th:field="*{storeName}"
required="required"/>
<div class="invalid-feedback">
Please provide a store name.
</div>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="addStatus">Status</label>
<select id="addStatus" class="form-control" th:field="*{status}">
<option th:value="Ready_to_service">Ready to service</option>
<option th:value="Temporarily_closed">Temporarily closed</option>
<option th:value="Closed">Closed</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<button class="btn btn-success" type="submit" th:text="Save"></button>
</div>
</form>
</div>
</div>
</div>
</div>
Not sure if you found the solution or not as it looks like an old question.
You are missing to let Thymeleaf know about the field specific error. You havn't bind the invalid-feedback class to the "field" error. Try below piece of code.
<input type="text" class="form-control" id="addstoreName" th:field="*{storeName}" required="required"/>
<div class="invalid-feedback" th:if="${#fields.hasErrors('storeName')}" th:errors="*{storeName}"></div>
Take a look at the working example here. Here it will look like this:

Thymeleaf client side validation

I am new to thymeleaf and I working on a login form. I have found a simple example where there is login input text and password fields.
I have included the project in my system. When I click the login button without filling username and password section, a please fill in details ballon pops up. I have not configured it anywhere, but would like to know from it is getting popped up. Below is the code
<div class="row" style="margin-top:20px">
<div class="form-group " align="right">
</br> </br> </br> </br> </br></br> </br> </br> </br>
<form th:action="#{/login}" method="post">
<fieldset>
<h2 class="form-heading">Log in</h2>
<div th:if="${param.error}">
<div class="alert alert-danger">
Invalid username and password.
</div>
</div>
<div th:if="${param.logout}">
<div class="alert alert-info">
You have been logged out.
</div>
</div>
<div class="form-group">
<input type="text" name="username" id="userName" class="form-control input-lg"
placeholder="UserName" required="true" autofocus="true"/>
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg"
placeholder="Password" required="true"/>
</div>
<div class="row">
<button class="btn btn-default" role="button">Log In</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>

instead of clicking on the element it clicks on the most top-left side of the window

I am using Java and Selenium to write a test. I have an element (a drop down menu) that I want to click on that I used action.click, elemnet.clcik javascript executor. But instead of the element they all click on the most top-left side of the window.
I opened developer tool window and checked my xpath that I finding the element with and it's correct, i mean when I copy paste the xpath at the DOM it shows the element. why do they click on top-left side of the window?
below is the snippet of the dom that the element is in there:
<div class="verde-form-row workflowTask-row even">
<h1><span class="by-label">Service</span>: Platinum <span class="unitOrLld">(Acres)</span></h1>
<form class="verde-form-fields fieldInfo-fields " data-task="">
<div data-create-with="" class="form-field-wrapper task-create-with">
<div class="select2-container select2-container-multi verde-select2 undefined" id="s2id_autogen11438">
<ul class="select2-choices">
<li class="select2-search-field">
<label for="s2id_autogen11439" class="select2-offscreen"></label>
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input select2-default" id="s2id_autogen11439" placeholder="" style="width: 290px;" aria-activedescendant="select2-result-label-11977"> </li>
</ul>
</div>
<input data-selector="" type="hidden" name="field" value="" tabindex="-1" class="select2-offscreen">
</div>
<div class="create-task-info">
<div class="task-comments">
<input type="text" name="comments" placeholder="Comments" value="">
<button type="button" data-action="cancel">Cancel</button>
</div>
<div class="task-lab">
<div class="form-field-wrapper" data-field-area="">
<input type="number" step="any" min="0" name="field_area" placeholder="Field Area" value="">
<label class="task-field-area-unit" data-field-area-units="">Acres</label>
</div>
<div data-lab-priority="" class="form-field-wrapper">
<div class="select2-container verde-select2 undefined select2-allowclear" id="s2id_autogen12036">
<a href="javascript:void(0)" class="select2-choice" tabindex="-1"> <span class="select2-chosen" id="select2-chosen-12037">Applied (Pre Buy)</span><abbr class="select2-search-choice-close"></abbr> <span class="select2-arrow" role="presentation"><b role="presentation"></b></span>
</a>
<label for="s2id_autogen12037" class="select2-offscreen"></label>
<input class="select2-focusser select2-offscreen" type="text" aria-haspopup="true" role="button" aria-labelledby="select2-chosen-12037" id="s2id_autogen12037">
<div class="select2-drop select2-display-none select2-with-searchbox">
<div class="select2-search">
<label for="s2id_autogen12037_search" class="select2-offscreen"></label>
<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" role="combobox" aria-expanded="true" aria-autocomplete="list" aria-owns="select2-results-12037" id="s2id_autogen12037_search" placeholder=""> </div>
<ul class="select2-results" role="listbox" id="select2-results-12037"> </ul>
</div>
</div>
<input data-selector="" type="hidden" name="lab_priority_type" value="11" tabindex="-1" title="" class="select2-offscreen">
</div>
<div data-lab-analysis="" class="form-field-wrapper"></div>
</div>
</div>
</form>
and this is my xpath:
//div[./h1[contains(text(),'Platinum')]]//span[text()='Applied (Pre Buy)']
a hint: when I click on any other parts of the window and then click on the element it works !!!

Invalid location of tag (form) in JSP Page

here is my code, I have used this code in jsp now when i am using form tag it is showing--invalid location of tag (form)
<div class="col-sm-12">
<div id="collapseTwo" class="panel-collapse collapse">
<div class="panel-body classPadding">
<form role="form" id="js-upload-form" > //INVALID LOCATION OF TAG(FORM)
<div class="col-sm-8 md-pl-0">
<div class="form">
<div class="form-group">
<input type="file" onchange="loadFile(event)" name="econoDataFile" accept="image/*" id="js-upload-files">
</div>
<h5 id="id-text-setting">Upload an Image of size 192*192</h5>
<img id="output" src="" class="save-img" />
</div>
</div>
<div class="col-sm-4">
<button class="btn btn-sm btn-primary" type="submit" id="js-upload-submit">Save</button>
</div>
</form>
<div class="form-group col-md-6 md-pl-0">
<span>Send to a Segment</span> <select id="segment-name" class="form-control">
<option value="-1" >All Subscribers</option> </select>
</div>
</div>
</div>
</div>
I had the same error, in my case the problem was that I had the form nested inside another form

Null value is getting passed to the Servlet from my jQuery script

I am passing a value from a jsp page to bootstrap modal using jQuery and it is working. I want to pass the same value from bootstrap modal to the servlet. I tried with ajax, post, nothing seems to be working. Here is my html:
<div class="container" style="padding-top: 60px;" >
<select class="createAlarm" id="createAlarm" name="metrics">
<option value="cpuUsage">CPU Usage</option>
<option value="memoryUsage">Memory Usage</option>
<option value="diskRead">Disk Read</option>
<option value="diskWrite">Disk Write</option>
<option value="diskUsage">Disk Usage</option>
<option value="netUsage">Net Usage</option>
</select>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-whatever="Create Alarm">Create Alarm</button>
</div>
<!-- Modal- Create Alarm -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Create Alarm</h4>
</div>
<form action="/ProjectName/createAlarm" method="post" id="addcard" class="form-horizontal" role="form">
<div class="modal-body" style="height: 170px;">
<div class="form-group" style="height: 30px;">
<label for="title" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="alarmName">
</div>
</div>
<div class="form-group" style="height: 30px; margin-bottom:30px;">
<label for="title" class="col-md-3 control-label">Description</label>
<div class="col-md-9">
<textarea class="form-control" name="desc"></textarea>
</div>
</div>
<div class="form-group">
<label for="priority" id="priority" name="priority" class="col-md-3 control-label">
<input type="text" class="form-control" name="name">
</label>
<div class="col-md-9">
<div class="col-md-3">
<select name="sign" class="form-control">
<option value="lessthan"><</option>
<option value="greaterthan">></option>
<option value="lessthanequalto"><=</option>
<option value="greaterthanequalto">>=</option>
</select>
</div>
<div class="col-md-3">
<input type="text" class="form-control" name="threshold">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button class="btn btn-primary" id="formSubmit" type="submit">Create Alarm</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Here is my jQuery part:
<script>
$('#myModal').on('show.bs.modal', function(e) {
var metrics_key = $('.createAlarm').val();
var metrics_label = $(".createAlarm option:selected").text();
// Now you have the key and label in variables.
// Write the key into the textfield.
$('#myModal input[name="name"]').val(metrics_key);
// Change the HTML of an element to the label.
$('#myModal label[for="priority"]').text(metrics_label);
$.post("/CMPE283_Project2/createAlarm", { val : $("#priority").text()});
alert($('#priority').text());
});
My Servlet:
String Metric = request.getParameter("val");
But, I am getting null for the String Metric. But alert pop up after clicking 'Create Alarm' button shows the correct value I want to pass the servlet. Please help. Thanks.
Your post looks ok, I believe it's just a matter of jquery syntax for accessing controls.
In particular, I'd expect a text input with id="priority" (not just a label as it appears in your code), and then you access it with '.val()' and not 'text()'
<input type="text" id="priority" ... />
$.post('your url', {priority: $("#priority").val()} ...
At least this works for me (jquery version 2.1.3). If you want to make sure, you can just start by posting hard coded data such as {priority: '7'}

Categories