Is there any built in support in jQuery for basic assertion checking, primarily of things like \'expected number of returned elements\'.
For instance I may have a simple
It doesn't look like there is anything built-in. But writing an extension isn't too hard:
$.fn.assertSize = function(size) {
if (this.length != size) {
alert("Expected " + size + " elements, but got " + this.length + ".");
// or whatever, maybe use console.log to be more unobtrusive
}
return this;
};
Usage is exactly as you propose in your question.
$("#btnSignup").assertSize(1).click(function() {
return validateForm();
);
Note that in its current form the function returns successfully even if the assertion fails. Anything you have chained will still be executed. Use return false;
instead of return this;
to stop further execution of the chain.