nightwatch assert ALL elements, not ANY - nightwatch.js

I'm trying to test that, when the Submit button is clicked on an empty form, all the "please fill in this field" labels are displayed.
I'm doing so with this:
page.click('#btn_submit');
page.expect.element('#validation_label_required').to.be.visible;
where #validation_label_required is represented by the CSS selector:
input[required] ~ p.error-message-required
However, this test passes if ANY of the validation labels are visible. The test should only pass if they ALL are.
How can I achieve this?

You will need to create a custom assertion for that where you locate all elements by selenium commands and then loop to verify condition. It should look something like this
var util = require('util');
exports.assertion = function (elementSelector, expectedValue, msg) {
this.message = msg || util.format('Testing if elements located by "%s" are visible', elementSelector);
this.expected = expectedValue;
this.pass = function (value) {
return value === this.expected;
};
this.value = function (result) {
return result;
};
this.command = function (callback) {
var that = this.api;
this.api.elements('css selector',elementSelector, function (elements) {
elements.value.forEach(function(element){
that.elementIdDisplayed(element.ELEMENT,function(result){
if(!result.value){
callback(false);
}
});
});
callback(true);
});
return this;
};
};

I've just ended up with another custom assertion that check how many elements are visible by given css selector.
/**
* Check how many elements are visible by given css selector.
*
*/
var util = require('util');
exports.assertion = function(elementSelector, expectedCount, msg) {
this.message = msg || util.format('Asserting %s elements located by css selector "%s" are visible', expectedCount, elementSelector);
this.expected = expectedCount;
this.count = 0;
this.pass = function(value) {
return value === this.expected;
};
this.value = function(result) {
return this.count;
};
this.command = function(callback) {
var me = this, elcount = 0;
this.count = 0;
this.api.elements('css selector', elementSelector, function(elements) {
if(elements.value && elements.value.length > 0){
elcount = elements.value.length;
}else{
return callback(false);
}
elements.value.forEach(function(element) {
me.api.elementIdDisplayed(element.ELEMENT, function(result) {
if (result.value) {
me.count++;
}
elcount--;
if (elcount === 0) {
callback(me.count);
}
});
});
});
};
};

Related

How do I add html tags in jquery plugins?

I am doing the live search using the jquery plugins. When I tried to search that doesn't exist, it only shows the table. I would like to put some message "No result found" if it doesnt exist. The question is how can I add message "No result found"
Note: In my codes I add some validation, the user need input minimum of 3 characters
/**
**options to have following keys:
**searchText: this should hold the value of search text
**searchPlaceHolder: this should hold the value of search input box placeholder
**/
(function($)
{
$.fn.tableSearch = function(options)
{
if(!$(this).is('table'))
{
return;
}
var tableObj = $(this),
searchText = (options.searchText)?options.searchText:'Search: ',
searchPlaceHolder = (options.searchPlaceHolder)?options.searchPlaceHolder:'',
divObj = $('<div style="font-size:20px;">'+searchText+'</div><br /><br />'),
inputObj = $('<input style="min-width:25%;max-width:50%;margin-left:1%" type="text" placeholder="'+searchPlaceHolder+'" />'),
caseSensitive = (options.caseSensitive===true)?true:false,
searchFieldVal = '',
pattern = '';
inputObj.off('keyup').on('keyup', function(){
searchFieldVal = $(this).val();
if(searchFieldVal.length == 0)
{
tableObj.find('tbody tr').show();
}
else if(searchFieldVal.length >= 3)
{
pattern = (caseSensitive)?RegExp(searchFieldVal):RegExp(searchFieldVal, 'i');
tableObj.find('tbody tr').hide().each(function()
{
var currentRow = $(this);
currentRow.find('td').each(function()
{
var result = "No result";
$("tbody tr").append(result);
if(pattern.test($(this).html()))
{
currentRow.show();
return false;
}
});
});
}
});
tableObj.before(divObj.append(inputObj));
return tableObj;
}
}(jQuery));
Here into JQ plugin(Posted at your question), the handler for empty result is exist. See piece of code from it.
else if(searchFieldVal.length >= 3)
{
pattern = (caseSensitive)?RegExp(searchFieldVal):RegExp(searchFieldVal, 'i');
tableObj.find('tbody tr').hide().each(function()
{
var currentRow = $(this);
currentRow.find('td').each(function()
{
var result = "No result";
$("tbody tr").append(result);
if(pattern.test($(this).html()))
{
currentRow.show();
return false;
}
});
});
}
Paraphrase you mistaken at your end. Re check it.

Chain filter conditions dynamically

How to chain multiple conditions in RethinkDB? This is what I got right now and what works if I only pass live or sports as a parameter. As soon as I pass the live and sports parameter, sports obviously always overwrites the filter variable and the live parameter is ignored.
app.get('/bets', function (req, res) {
var live = req.query.live;
var sports = req.query.sports;
var filter = {};
if (live === undefined) {
filter = r.or(r.row('live').eq(0), r.row('live').eq(1));
} else {
filter.live = parseInt(live);
}
if (sports !== undefined) {
var sports = sports.split(',');
filter = function (doc) {
return r.expr(sports).contains(doc("sport"));
}
}
r.table('bets').filter(filter).limit(100).run(connection, function(err, cursor) {
// ...
});
});
You can chain filters with RethinkDB.
Something along the lines of this (warning, untested) :
app.get('/bets', function (req, res) {
var live = req.query.live;
var sports = req.query.sports;
var liveFilter, sportFilter;
if (live === undefined) {
liveFilter = r.or(r.row('live').eq(0), r.row('live').eq(1));
} else {
liveFilter = function (doc) { return true; };
}
if (sports !== undefined) {
sports = sports.split(','); // no need to redefine the variable here
sportFilter = function (doc) {
return r.expr(sports).contains(doc("sport"));
}
} else {
sportFilter = function (doc) { return true; };
}
r.table('bets')
.filter(liveFilter) // apply the first filter
.filter(sportsFilter) // apply the second filter
.limit(100)
.run(connection, function(err, cursor) {
// ...
});
});
Alternatively you could make one filter function that would handle both the live and sport filters (equally untested, this is to get you started) :
app.get('/bets', function (req, res) {
var live = req.query.live;
var sports = req.query.sports.split(',');
var filter = function(doc){
var sportPass, livePass;
if (live === undefined) {
livePass = r.or(r.row('live').eq(0), r.row('live').eq(1))(doc);
} else {
livePass = parseInt(live); // not sure what you meant by filter.live here
}
if (sports !== undefined) {
sportPass = r.expr(sports).contains(doc("sport"));
}
return sportPass && livePass;
};
r.table('bets').filter(filter).limit(100).run(connection, function(err, cursor) {
// ...
});
});

Bootstrap Multiselect filtering values based on another dropdown

I'm working on cascading the multi-select based on the values of the data-attributes on another.
I have this method which is called inside the onChanged event of the parent. By parent I mean what to filter the child by i.e
Parent = Department Multiselect
Child = Staff Multiselect.
The child element has a data attribute of data-departmentid.
function cascadeMultiselect(control, targetControl, key) {
this.control = control;
this.targetControl = targetControl;
this.key = key;
this.toHide = [];
this.toShow =[];
//Get controls selectedIds
this.selectedIds = function() {
var selected = [];
_.each($(this.control + " option:selected"), function(c) {
selected.push($(c).val());
});
return selected;
};
//Now filter
this.filter = function() {
//Get target control attribute values
_.each($(targetControl + " option"), function(tc) {
//Use the val as an identifier
var val = $(tc).val();
var data = $(tc).attr("data-" + key);
data = data.split(",");
var isMatch = anyMatchInArray(data, this.selectedIds());
if(!isMatch){
$(tc).hide();
}
});
}
this.filter();
$(targetControl).multiselect('rebuild');
}
It's being called like so:
onChange: function() {
cascadeMultiselect('#departmentlist', '#stafflist', "DepartmentID");
}
The problem is I can't hide the elements. The filter works just fine, I've tried:
$(tc).hide(); // tc = targetControl option
I've also tried to refresh instead of rebuild.
Since it seems the only way to do this was to store the values of the multiselect, and then remove / add the relevant values.
I decided to use a rudimentary Cache class:
var Cache = (function () {
this.all = [];
function Cache(control) {
this.control = control;
}
Cache.prototype.getAll = function () {
return this.all;
};
Cache.prototype.setAll = function (all) {
this.all = all;
};
return Cache;
})();
Function now looks like:
function cascadeMultiselect(control, targetControl, key, cache) {
this.control = control;
this.targetControl = targetControl;
this.key = key;
this.toHide = [];
this.toShow =[];
//To reset the multiselect
this.reset = function(){
$(targetControl).html('');
$(targetControl).multiselect('dataprovider', cache.all)
}
//Get controls selectedIds
this.selectedIds = function() {
var selected = [];
_.each($(this.control + " option:selected"), function(c) {
selected.push($(c).val());
});
return selected;
};
//Now filter
this.filter = function() {
//Get target control attribute values
_.each($(targetControl + " option"), function(tc) {
//Use the val as an identifier
var val = $(tc).val();
var data = $(tc).attr("data-" + key);
data = data.split(",");
var isMatch = anyMatchInArray(data, this.selectedIds());
console.log($(tc));
if(!isMatch){
$(tc).remove();
}
});
}
//If nothing selected then reset the multiselect
if(this.selectedIds().length == 0){
this.reset();
return;
}else{
this.filter();
}
$(targetControl).multiselect('rebuild');
}
When I first populate the multiselect with the dataprovider I add the data to the cache:
if(cache != null){
cache.setAll(this.dataToAdd);
}

SlickGrid filter not working

I am fairly new to SlickGrid. I am trying to make SlickGrid filter work but no luck. I am following the example (http://mleibman.github.io/SlickGrid/examples/example4-model.html).
Below is my source code.
$(document).ready(function() {
var tName;
$('#submit').click(function(e) {
tName = $('#source option:selected').text();// name1
tName = tName.trim();
$.ajax({
url : 'someUrl',
type : 'GET',
cache : false,
success : function(d) {
var grid;
var searchString = "";
var data = [];
var columns = new Array();
var cols = d[0].columns;
var pkColNames = d[0].pkColNames;
for (var j=0; j< cols.length; j++) {
var key = {id: cols[j].colName, name: cols[j].colName, field: cols[j].colName, width: 200, sortable:true, editor: Slick.Editors.LongText};
columns[j] = key;
}
var options = {
editable: true,
enableAddRow: false,
enableCellNavigation: true,
asyncEditorLoading: false,
enableColumnReorder:true,
multiColumnSort: false,
autoEdit: false,
autoHeight: false
};
function myFilter(item, args) {
return true;// Let us return true all time ?
}
for (var i = 0; i < d.length; i++) {
var tempData = (data[i] = {});
var title = null;
var val = null;
for (var q = 0; q < d[i].columns.length; q++) {
title = d[i].columns[q].colName;
val = d[i].columns[q].colValue;
tempData[title] = val;
}
}
var dataView = new Slick.Data.DataView({ inlineFilters: true });
grid = new Slick.Grid("#myGrid", dataView, columns, options);
dataView.setPagingOptions({
pageSize: 25
});
var pager = new Slick.Controls.Pager(dataView, grid, $("#myPager"));
var columnpicker = new Slick.Controls.ColumnPicker(columns, grid, options);
grid.setSelectionModel(new Slick.CellSelectionModel());
grid.onAddNewRow.subscribe(function(e, args) {
// Adding a new record is not yet decided.
});
grid.onCellChange.subscribe(function (e) {
var editedCellNo = arguments[1].cell;
var editedColName = grid.getColumns()[editedCellNo].field;
var newUpdatedValue= arguments[1].item[grid.getColumns()[editedCellNo].field];
var editedColType = "";
for (var cnt = 0; cnt < cols.length; cnt++) {
if (editedColName == cols[cnt].colName) {
editedColType = cols[cnt].colType;
break;
}
}
var pkKeyValue="";
for (var v=0; v <pkColNames.length;v++) {
for (var p=0; p<grid.getColumns().length; p++) {
if (pkColNames[v] == grid.getColumns()[p].field) {
var value = arguments[1].item[grid.getColumns()[p].field];
pkKeyValue += "{"+pkColNames[v] + '~' +getColDbType(grid.getColumns()[p].field) + ":"+value+"},";
break;
}
}
}
function getColDbType(colName) {
for (var c = 0; c < cols.length; c++) {
if (colName == cols[c].colName) {
return cols[c].colType;
}
}
}
pkKeyValue = pkKeyValue.substring(0, pkKeyValue.length-1);
$.ajax({
url: 'anotherUrl',
type:'GET',
dataType:'text',
success: function(f) {
bootbox.alert("Data updated successfully");
},
error: function() {
bootbox.alert("Error - updating data. Please ensure you are adding the data in right format.");
grid.invalidateAllRows();
grid.render();
}
});
});
grid.onClick.subscribe(function (e) {
//do-nothing
});
dataView.onRowsChanged.subscribe(function(e, args) {
grid.updateRowCount();
grid.invalidateRows(args.rows);
grid.render();
});
grid.onSort.subscribe(function(e, args) {
// args.multiColumnSort indicates whether or not this is a multi-column sort.
// If it is, args.sortCols will have an array of {sortCol:..., sortAsc:...} objects.
// If not, the sort column and direction will be in args.sortCol & args.sortAsc.
// We'll use a simple comparer function here.
var comparer = function(a, b) {
return a[args.sortCol.field] > b[args.sortCol.field];
}
// Delegate the sorting to DataView.
// This will fire the change events and update the grid.
dataView.sort(comparer, args.sortAsc);
});
// wire up the search textbox to apply the filter to the model
$("#txtSearch").keyup(function (e) {
console.log('Called...txtSearch');
Slick.GlobalEditorLock.cancelCurrentEdit();
// clear on Esc
if (e.which == 27) {
this.value = "";
}
searchString = this.value;
updateFilter();
});
function updateFilter() {
console.log("updateFilter");
dataView.setFilterArgs({
searchString: searchString
});
dataView.refresh();
}
dataView.beginUpdate();
dataView.setItems(data, pkColNames);
dataView.setFilterArgs({
searchString: searchString
});
dataView.setFilter(myFilter);
dataView.endUpdate();
},
error : function() {
bootbox.alert("Invalid user");
}
});
});
});
Your function myFilter() is always returning true so of course it will never work. The example that you looked at, was to filter something specific. I would recommend that you look at the following example to have a generic filter. From the example, simply type the text you are looking on a chosen column and look at the result... see example below (from SlickGrid examples).Using fixed header row for quick filters
In case you want a more in depth conditional filters ( > 10, <> 10, etc...), please take a look at my previous answer on how to make this kind of filtering possible, see my previous answer below:SlickGrid column type
Hope that helps you out

multiple knockout validators on an observablearray

I tried to define multiple custom validation rules under a observable array, I was referring to https://github.com/ericmbarnard/Knockout-Validation/wiki/Custom-Validation-Rules.
Following is my observablearray with the validation calls:
this.WeeklyData = ko.observableArray([]).extend({
validation: [
{
validator : fminIncrements,
message: 'use 15 min increments'
},
{
validator: ValidateMinMax,
message: "Invalid min/max value"
}
]
});
var ValidateMinMax = function (valueArray) {
var check = true;
ko.utils.arrayFirst(valueArray, function (value) {
if (parseInt(value.Val(), 10) < 0 || parseInt(value.Val(), 10) > 168) {
check = false;
return true;
}
});
return check;
};
var fminIncrements = function (valueArray) {
var check = true;
ko.utils.arrayFirst(valueArray, function (value) {
if (parseInt(value.Val(), 10) % 15 !== 0) {
check = false;
return true;
}
});
return check;
};
when I do this only the first rule fires. I debugged, and it doesn't even hit the second one. Any idea?
Thanks in advance for any help.
I believe its because you are using the ko.utils.arrayFirst(). If you use the ko.utils.arrayForEach() instead to check for every case then it shouldn't return at the first occurrence.

Resources