Simple UI testing a button click with karma and qUnit - qunit

I have figured out how to test my code with the karma test runner, but I cannot figure out how to test the UI features on a web page.
I have a simple calculator program (calculator.js):
window.onload = function () {
var okResult = /^.*(\+|\*|-|÷)\d$|^\d$|^.*\d((\+|\*|-|÷)|\d)$/,
i, tds = document.getElementsByTagName("td");
var setResult = function (t) {
document.getElementsByTagName("th")[0].innerHTML = t;
};
var appendResult = function (t) {
document.getElementsByTagName("th")[0].innerHTML += t;
};
var getResult = function () {
return document.getElementsByTagName("th")[0].innerHTML;
};
for (i = 0; i < tds.length; i++) {
tds[i].onclick = function () {
var r;
if (this.innerHTML == '=') {
setResult(eval(getResult().replace(/÷+?/g, '/')));
} else if (this.innerHTML == 'clr') {
setResult("0");
} else if (getResult() == '0') {
setResult(this.innerHTML);
} else {
appendResult(this.innerHTML);
}
if (!okResult.test(getResult())) {
r = getResult();
setResult(r.substring(0, r.length - 1));
}
};
}
};
With this simple table in the HTML DOM (calculator/index.html):
<table>
<tr>
<th id="results" colspan="4">0</th>
</tr>
<tr>
<td colspan="3"> </td>
<td>clr</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
<td>÷</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
<td>*</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>-</td>
</tr>
<tr>
<td>.</td>
<td>0</td>
<td>=</td>
<td>+</td>
</tr>
</table>
I want to test it by triggering click events on the cells found in the DOM. For example (calculator-spec.js):
test("Calculator initially displays 0", function () {
equal( $('td#results').text(), "0", "Initial display is 0" );
});
test("Calculator can add numbers", function () {
$('td:contains("1")').trigger('click');
$('td:contains("+")').trigger('click');
$('td:contains("1")').trigger('click');
$('td:contains("=")').trigger('click');
equal( $('td#results').text(), "2", "Initial display is 0" );
});
I am trying to automate testing with karma, and in my karma.conf.js file I have:
// frameworks to use
frameworks: ['qunit'],
// list of files / patterns to load in the browser
files: [
'http://code.jquery.com/jquery-1.10.2.min.js',
'**/Examples/Calculator/Complete/calculator.js',
'test/calculator/calculator-spec.js',
{pattern: '**/Examples/Calculator/Complete/index.html', watched: false, included: false, served: true}
],
How do I perform UI testing using karma. How can I simulate mouse and keyboard events and check the resulting DOM using either qUnit or jasmine?

I've had to use the DOM elements click method:
$('td:contains("1")')[0].click();

Related

laravel vue send array to backend

I want to send array of id's to backend with one button from vuejs table but i get error 500.
Logic
Check the check boxes
Collect the id's
Send id's to back-end when click on button
update the view
Code
template
<table class="table table-dark table-hover table-bordered table-striped">
<thead>
<tr>
<th class="text-center" width="50">
//the button
<button class="btn btn-outline-danger" #click="withdraw(index)">Withdraw</button>
</th>
<th class="text-center" width="50">#</th>
<th class="text-center">Amount</th>
</tr>
</thead>
<tbody>
<tr v-for="(income,index) in incomes" v-bind:key="index">
<td class="text-center">
//check box input
<input v-if="income.withdraw == '0'" type="checkbox" :id="income.id" :value="income.amount" v-model="checkedNumbers">
</td>
<td class="text-center">{{index+1}}</td>
<td class="text-center">Rp. {{formatPrice(income.amount)}}</td>
</tr>
<tr>
<td colspan="2"></td>
<td>
<span>Withdraw for today, Sum: <br> Rp. {{ formatPrice(sum) }}</span>
</td>
</tr>
</tbody>
</table>
script
export default {
data() {
return {
incomes: [],
checkedNumbers: [],
}
},
computed: {
sum() {
return this.checkedNumbers.reduce(function (a, b) {
return parseInt(a) + parseInt(b);
}, 0);
}
},
methods: {
withdraw(index) {
let checkedids = this.incomes[index]
axios.post(`/api/withdrawbutton/`+checkedids).then(response => {
this.income[index].withdraw = '1'
this.$forceUpdate()
});
}
}
}
route
Route::post('withdrawbutton/{id}', 'IncomeController#withdrawbutton');
controller
public function withdrawbutton($id)
{
$dowithdraw = Income::where('id', $id)->get();
$dowithdraw->withdraw = '1';
$dowithdraw->save();
return response()->json($dowithdraw,200);
}
Any idea where is my mistake and how to fix it?
......................................................................................................................
Don't send the list as a GET parameter, send it as a POST:
let params = {}
params.ids = this.checkedNumbers
axios.post(`/api/withdrawbutton/`, params)
.then(response => {
this.income[index].withdraw = '1'
this.$forceUpdate()
});
Controller
public function withdrawbutton(Request $request)
{
$dowithdraws = Income::whereIn('id', $request->input('ids', []));
$dowithdraws->update(['withdraw' => '1']);
return response()->json($dowithdraws->get(), 200);
}
Route
Route::post('withdrawbutton/', 'IncomeController#withdrawbutton');
And I don't think you need to update anything in the front because you already have them checked (if you want to keep them checked)

Differ between 2 or more click events called from javascript code

var option,
Switch (option)
{
case "A":
document.getElementById("cell").click();
break;
case "B":
document.getElementById("cell").click();
break;
default:
break;
},
clickEventHandlerForCell(event){
//When case A
alert("I am fired from case A");
// When case B
alert("I am fired from case B");
}
A button is clicked from Javascript code. How to send a value to the handler function to tell, from where it was called? I read that there is a method to tell the difference between the real click and fake click. But I couldn't find a question differing 2 fake links.'Pure'Javascript is preferable. Thanks.
What I thought you meant
The event object holds what was clicked. So you can handle the data that way.
function clicked(event) {
console.log(event.target);
console.log(event.target.getAttribute("data-item"));
}
document.getElementById("tab").addEventListener("click", clicked);
var tds = document.getElementsByTagName("td");
tds[0].click();
tds[1].click();
<table id="tab">
<tbody>
<tr>
<td data-item="1">1</td>
<td data-item="2">2</td>
</tr>
</tbody>
</table>
What you actually wanted
function clicked(event) {
console.log(event.target.getAttribute("data-action"));
event.target.removeAttribute("data-action");
}
document.getElementById("tab").addEventListener("click", clicked);
var tds = document.getElementsByTagName("td");
tds[0].setAttribute("data-action", "A");
tds[0].click();
tds[0].setAttribute("data-action", "B");
tds[0].click();
<table id="tab">
<tbody>
<tr>
<td>1</td>
</tr>
</tbody>
</table>

Duplicated List of DropdownList when ajax update?

I have a Ajax Jquery function:
function UpdateValue() {
$(document.body).on("change",".quantity", function () {
var ProID = $(this).attr("data");
var Quantity = $(this).val();
$.ajax({
type: "GET", url: "/Cart/UpdateValue",
data: { ProID: ProID, quantity: Quantity },
success: function (data) {
$("#cartbox").html(data);
}
}
);
$.ajaxSetup({
cache: false
});
});
}
call UpdateValue in Cart Controller:
public PartialViewResult UpdateValue(Cart cart,int ProID, int quantity)
{
List<SelectListItem> items = new List<SelectListItem>();
for (int i = 1; i <= 10; i++)
{
items.Add(new SelectListItem { Text = i.ToString(),
Value = i.ToString() });
}
ViewBag.Items = items;
Product product = repository.Products.FirstOrDefault(p => p.ProductID
== ProID);
if (product != null)
{
cart.UpdateItem(product, quantity);
}
CartIndexViewModel ptview = new CartIndexViewModel { Cart = cart,
ReturnUrl = "/" };
return PartialView(ptview);
}
When the ajax function success, it returns UpdateValue View. But the Dropdown List always changes the same in each row. How can i pass the selected value from the Index View after ajax update?
Here is my UpdateValue View Code:
<table id="cartbox">
<thead>
<tr>
<th>Tên hàng</th>
<th>Số lượng</th>
<th>Đơn giá</th>
<th colspan="2" style="width:70px">Thành tiền</th>
</tr>
</thead>
<tbody>
#foreach (var line in Model.Cart.Lines)
{
<tr>
<td>#line.Product.Name
</td>
<td>#Html.DropDownList("Quantity", new SelectList(ViewBag.Items as System.Collections.IList, "Value", "Text", line.Quantity), new { data = line.Product.ProductID, #class = "quantity" })</td>
<td style="color:#3A9504;margin-left:3px">#string.Format("{0:00,0 VNĐ}", line.Product.Price)</td>
<td>#string.Format("{0:00,0 VNĐ}", (line.Quantity * line.Product.Price))</td>
<td align="center" style="width:10px"><img src="#Url.Content("~/Content/Images/delete.png")" style="padding-right:10px" /></td>
</tr>
}
</tbody>
<tfoot>
<tr style="border-top-style:solid;border-top-color:#DFDFDF;border-top-width:1px;">
<td colspan="3" align="right" style="border-right-color:#808080;border-right-style:solid;border-right-width:1px;text-align:right"><b>Tổng tiền:</b></td>
<td style="text-align: center"><b>#string.Format("{0:00,0 VNĐ}", Model.Cart.ComputeTotalValue())</b></td>
<td></td>
</tr>
</tfoot>
</table>
If I understand you correctly then your problem is that after updating the data in the dropdown list you lose the selection in that dropdown list?
If so then you would need to add this to your success handler in JavaScript:
success: function (data) {
$("#cartbox").html(data);
$("#cartbox").find(".quantity").val(Quantity);
}

make jquery plugin not share private variable in same plugin

<script>
(function () {
jQuery.fn.szThreeStateColor = function (settings) {
var cfg = {
"overBgColor": "green",
"overFgColor": "white",
"clickBgColor": "blue",
"clickFgColor": "white"
};
if(settings) {
$.extend(cfg, settings);
}
var clickIdx = -1;
$thisObj = $(this);
var iniBgColor = $thisObj.find("tbody td").css("background-color");
var iniFgColor = $thisObj.find("tbody td").css("color");
var iniHeight = $thisObj.find("tr").css("height");
$thisObj.find("tbody tr").bind("mouseover", function (e) {
if($(this).index() != clickIdx) {
$(this).css({
"background-color": cfg.overBgColor,
"color": cfg.overFgColor
});
}
});
$thisObj.find("tbody tr").bind("mouseout", function (e) {
if($(this).index() != clickIdx) {
$(this).css({
"background-color": iniBgColor,
"color": iniFgColor
});
}
});
$thisObj.find("tbody tr").bind("click", function (e) {
//console.log($(this).index() + ":" + clickIdx);
if($(this).index() != clickIdx) {
if(clickIdx >= 0) {
$thisObj.find("tbody tr:eq(" + clickIdx + ")").css({
"background-color": iniBgColor,
"color": iniFgColor
});
}
$(this).css({
"background-color": cfg.clickBgColor,
"color": cfg.clickFgColor
});
clickIdx = $(this).index();
}
});
return this;
}
})($);
$(document).ready(function () {
$("#table1")
.szThreeStateColor({
"overBgColor": "#34ef2a",
"overFgColor": "#000000",
"clickBgColor": "#333333"
});
$("#table2").szThreeStateColor();
});
</script>
</HEAD>
<BODY>
<table id="table1" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
<table id="table2" width='300' border='1'>
<thead>
<tr><td>name</td><td>city</td><td>age</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
This plugin sets different cell colors when the events mouseover, mouseout, click are fired. The plugin works fine with a single table but works abnormally when multiple tables are used. Maybe the variable clickIdx is shared by each table. How can I prevent sharing of that variable?
You can do so by wrapping your plugin in return this.each(function() {...}).
jQuery.fn.szThreeStateColor = function (settings) {
// ...
return this.each(function() {
// variables that need to be private go in here
});
}

JavaScript to get user input from editable table cell and send to server via json

I created a table with five columns dynamically. Two (the second and third column) of the five columns should be editable on the fly. Each time when user click on one the editable table cell, JavaScript should catch the user input and send the data to the server in json format. I have problem catch the user input and send to the server. Please help. This is my sample code -
<!DOCTYPE html>
<html>
<head>
<title>Editable table</title>
<style type="text/css" title="currentStyle">
#import "css/table.css";
</style>
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
</head>
<body id="dt_example">
<div id="container">
<div class="full_width big">
Data table<br />
</div>
<div class="editab">
<table border="1">
<thead>
<tr>
<th>Contract Number</th>
<th>Current Status</th>
<th>Sale Balance Amount</th>
<th>Interest Rate</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<td>00123</td>
<td onClick="editTableCell(this)">A30</td>
<td onClick="editTableCell(this)">$1,500.00</td>
<td>3.99 %</td>
<td>140</td>
</tr>
<tr>
<td>00234</td>
<td onClick="editTableCell(this)">B20</td>
<td onClick="editTableCell(this)">$2,500.00</td>
<td>3.99 %</td>
<td>160</td>
</tr>
<tr>
<td>00345</td>
<td onClick="editTableCell(this)">C40</td>
<td onClick="editTableCell(this)">$3,500.00</td>
<td>3.99 %</td>
<td>180</td>
</tr>
<tr>
<td>00456</td>
<td onClick="editTableCell(this)">A20</td>
<td onClick="editTableCell(this)">$4,500.00</td>
<td>3.99 %</td>
<td>200</td>
</tr>
<tr>
<td>00567</td>
<td onClick="editTableCell(this)">B30</td>
<td onClick="editTableCell(this)">$5,500.00</td>
<td>3.99 %</td>
<td>225</td>
</tr>
<tr>
<td>00678</td>
<td onClick="editTableCell(this)">C10</td>
<td onClick="editTableCell(this)">$6,500.00</td>
<td>3.99 %</td>
<td>250</td>
</tr>
<tr>
<td>00789</td>
<td onClick="editTableCell(this)">A30</td>
<td onClick="editTableCell(this)">$7,500.00</td>
<td>3.99 %</td>
<td>300</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
var SelectState = false;
var SelectedElement = null;
var TextInput = null;
var CellText = null;
var txt = "test";
var idcount = 0;
function editTableCell( e ){
if ( SelectState == false ){
SelectedElement = e;
CellText = e.innerHTML;
e.innerHTML = "";
var objInput = document.createElement("input");
objInput.type = 'text';
objInput.value = CellText;
objInput.id = "txt" + idcount++;
objInput.onkeypress = editTextBox;
objInput.size = 15;
TextInput = objInput;
e.appendChild(objInput);
SelectState = true;
} else if (e != SelectedElement) {
SelectedElement.innerHTML = CellText;
SelectState = false;
}
}
function editTextBox( e ){
if (navigator.appName == "Microsoft Internet Explorer"){
e = window.event;
key = e.keyCode;
}
else if (navigator.appName == "Netscape"){
key = e.which;
}
if ( key == 13 ){
SelectedElement.innerHTML = TextInput.value;
SelectState = false;
}
else if ( key == 27 ){
SelectedElement.innerHTML = CellText;
SelectState = false;
}
}
/* var attrName = "":
var attrValue = "";
if ($('#test1')
{
attrName= "editField01";
attrValue = $(#test1).val();
}
if ($('#test2')
{
attrName= "editField02";
attrValue = $(#test2).val();
}
if ($('#test3')
{
attrName= "editField03";
attrValue = $(#test3).val();
}
var values = '{"' + attrName + '":' + attrValue + '}';
$.ajax({
url: serverUrl + "/abc/contract/" + poolId,
async: false,
type: "PUT",
data: JSON.stringify(values),
dataType: 'json',
processData: false,
contentType: 'application/json',
success: showResponse(json) {
// TODO: What info is returned in the data structure?
showResponse;
},
error: function(err) {
alert("Failed to update the attribute");
htmlErrorDialog(err.responseText);
}
});*/
function showResponse(json) {
if(json.success){
// handle successful response here
alert("user input from column sent successfully!");
} else {
// handle unsuccessful response here
alert("user input fail to send. Please try again");
}
}
</script>
</body>
</html>
You're not actually passing the json data to showResponse:
success: showResponse(json) {
// TODO: What info is returned in the data structure?
showResponse;
},
Pass it along as so, and make sure that json is an actual object and that you don't need to parse it first:
success: function(json) {
// check that json is an actual object via an alert
// alert(json);
showResponse(json);
},
EDIT: Okay after a lot of working around, I have a simple test case for making the fields editable. Please note it uses jquery, and comments are inline:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<!-- Date: 2011-05-10 -->
</head>
<body>
<form>
<table border="1">
<thead>
<tr>
<th>Contract Number</th>
<th>Current Status</th>
<th>Sale Balance Amount</th>
<th>Interest Rate</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<!-- The "identifier" class makes it so we have an id
to pass to our ajax script so we know what to change -->
<td class="identifier">00123</td>
<td class="editable">A30</td>
<td class="editable">$1,500.00</td>
<td>3.99 %</td>
<td>140</td>
</tr>
</tbody>
</table>
</form>
<script type="text/javascript">
// bind our event handler to all td elements with class editable
$('td.editable').bind('click', function() {
// Only create an editable input if one doesn't exist
if(!$(this).has('input').length) {
// Get the text from the cell containing the value
var value = $(this).html();
// Create a new input element with the value of the cell text
var input = $('<input/>', {
'type':'text',
'value':value,
// Give it an onchange handler so when the data is changed
// It will do the ajax call
change: function() {
var new_value = $(this).val();
// This finds the sibling td element with class identifier so we have
// an id to pass to the ajax call
var cell = $(this).parent();
// Get the position of the td cell...
var cell_index = $(this).parent().parent().children().index(cell);
// .. to find its corresponding header
var identifier = $('thead th:eq('+cell_index+')').html();
//ajax post with id and new value
$(this).replaceWith(new_value);
}
});
// Empty out the cell contents...
$(this).empty();
// ... and replace it with the input field that has the value populated
$(this).append(input);
}
});
</script>
</body>

Resources