Jasmine wait until HTML rendering after a function is done - jasmine

Lets say we have a form with a jquery validation. Now we create a simple Jasmine spec and want to test if the error message is visible if we submit an empty form.
My first step is to trigger the submit form event after that jquery validate will work and show the error messages. The time window until the error message will be displayed is really small (2ms) but too big for a Jasmine test. Currently with a setTimeout() it works but I think that is a bad way :(
I am new to Jasmine and I think there must be a better way? Something with spy?
Dummy spec for example:
describe("Lorem Impsum: ", function () {
it("Form validation shows error messages.", function () {
$("#MyForm").submit();
expect($(".error")).toBeVisible();
});
});

Using setTimeout or setInterval for polling may not be a bad way. If the page is complicated, periodic checks are simpler, than using MutationObserver. (This is a unit test; not an application.) If you choose the polling interval short enough, the test will not be so slow. For example:
describe("Lorem Impsum: ", function () {
it("Form validation shows error messages.", function (done) {
$("#MyForm").submit();
waitForElement(".error", function () {
expect($(".error")).toBeVisible();
done();
});
});
});
function waitForElement(selector, callback) {
var interval;
if ($(selector).length) {
callback();
} else {
interval = setInterval(function () {
if ($(selector).length) {
clearInterval(interval);
callback();
}
}, 10);
}
}
You will need to declare and call the done callback, so that Jasmine gets notified, when the test spec has finished.

Related

how to use callback when I click ajax in nightmarejs

lately I have been studing nightmare module I think it's very simple and useful but I have question.
how to use callback when I click ajax button
MyCode
var Nightmare = require('nightmare'),
nightmare = Nightmare();
nightmare
.goto('https://motul.lubricantadvisor.com/Default.aspx?data=1&lang=ENG&lang=eng')
.click('input[title="Cars"]')
.wait(1000)
.evaluate(function () {
//return $('#ctl00_ContentPlaceHolder1_lstModel option');
var links = document.querySelectorAll('#ctl00_ContentPlaceHolder1_lstMake option');
return [].map.call(links, function (e) {
return {value: e.value, name: e.text};
});
})
.end()
.then(function (items) {
console.log(items);
});
there is wait method. most people use wait methed I searched googling
.wait(1000)
I don't use wait method. because If it's network disconnect or slow. It's not good code
Could you help me callback method??
Thanks. So I have motify the code but It's doesn't work
var Nightmare = require('nightmare'),
nightmare = Nightmare();
nightmare
.goto('https://motul.lubricantadvisor.com/Default.aspx?data=1&lang=ENG&lang=eng')
.click('input[title="Cars"]')
.wait('#result > #ctl00_ContentPlaceHolder1_lstMake option')
.evaluate(function () {
$(document).ajaxSuccess(function () {
var links = document.querySelectorAll('#ctl00_ContentPlaceHolder1_lstMake option');
return [].map.call(links, function (e) {
return {value: e.value, name: e.text};
});
});
})
.end()
.then(function (items) {
console.log(items);
});
There are many ways to solve this. The easiest would be the following.
Suppose when an Ajax request finishes, it always changes something on the page. Most of these changes can be easily detected when waiting for specific elements to appear which can be matched by CSS selectors.
Let's say you click something and the result is written into the element matched by "#result". If there wasn't such an element before the click then you can wait until the existence of this element:
.click("button")
.wait("#result")
// TODO: do something with the result
You can also use CSS selectors to count things. For example, let's say there are ten elements that can be matched with "#result > a". If a click adds 10 more, then you can wait for the 20th using:
.click("button")
.wait("#result > a:nth-of-type(20)")
// TODO: do something with the result
The world of CSS selectors is pretty big.
Of course, you could use evaluate to add a general Ajax event handler like $(document).ajaxSuccess(fn) to be notified whenever some callback finished, but the source code of a page changes all the time. It would be easier to maintain your code if you would look for the results that can be seen in the DOM.
Use this, ajax callback..
$.ajax(url,{dataType: "json", type: "POST" })
.then(function successCallback( data ) { //successCallback
console.log(data);
}, function errorCallback(err) { //errorCallback
console.log(err);
});
// console.log(2);
});

casperjs waitfor behaving mysteriously

I am trying to test a flow
1.Ajax Request > Loader is visible
2.Response Received > a.Loader is hidden
b.Redirect to another page(where a interstitial is visible)
White testing them with casperJS I use the waitFor method, something like this.
casper.waitFor(function check() {
return this.evaluate(function() {
return $("#loader").is(":hidden");
});
}, function then() {
this.test.pass("Ajax request");
this.waitDone();
}, function timeout() { // step to execute if check has failed
this.echo("Timeout: page did not load in time...").exit();
},4000);
The thing is even if the condition is passed in check, then is not executed until the page is not redirected(read the flow, I am trying to test) and the test suite won't move to the next step.
Is there something I am missing here ?
Make sure your reference 'this' is located within a casper block:
casper.then(function() {
this.waitFor(function check() {
Possible quick fix without knowing more detail. Pass jQuery variable to evaluate.
this.evaluate(function($) {
You could also try:
casper.waitWhileVisible('#loader', function() {
// executes when #loader is hidden
});
docs located at: CasperJS waitWhileVisible

How to use events and event handlers inside a jquery plugin?

I'm triyng to build a simple animation jQuery-plugin. The main idea is to take an element and manipulate it in some way repeatedly in a fixed intervall which would be the fps of the animation.
I wanted to accomplish this through events. Instead of using loops like for() or while() I want to repeat certain actions through triggering events. The idea behind this: I eventualy want to be able to call multiple actions on certain events, like starting a second animation when the first is done, or even starting it when one animation-sequence is on a certain frame.
Now I tried the following (very simplified version of the plugin):
(function($) {
$.fn.animation = function() {
obj = this;
pause = 1000 / 12; //-> 12fps
function setup(o) {
o.doSomething().trigger('allSetUp');
}
function doStep(o, dt) {
o.doSomething().delay(dt).trigger('stepDone');
}
function sequenceFinished(o) {
o.trigger('startOver');
}
function checkProgress(o) {
o.on({
'allSetup': function(event) {
console.log(event); //check event
doStep(o, pause);
},
'stepDone': function(event) {
console.log(event); //check event
doStep(o, pause);
},
'startOver': function(event) {
console.log(event); //check event
resetAll(o);
}
});
}
function resetAll(o) {
/*<-
reset stuff here
->*/
//then start over again
setup(o);
}
return this.each(function() {
setup(obj);
checkProgress(obj);
});
};
})(jQuery);
Then i call the animation like this:
$(document).ready(function() {
$('#object').animation();
});
And then – nothing happens. No events get fired. My question: why? Is it not possible to use events like this inside of a jQuery plugin? Do I have to trigger them 'manualy' in $(document).ready() (what I would not prefer, because it would be a completely different thing – controling the animation from outside the plugin. Instead I would like to use the events inside the plugin to have a certain level of 'self-control' inside the plugin).
I feel like I'm missing some fundamental thing about custom events (note: I'm still quite new to this) and how to use them...
Thx for any help.
SOLUTION:
The event handling and triggering actually works, I just had to call the checkProgress function first:
Instead of
return this.each(function() {
setup(obj);
checkProgress(obj);
});
I had to do this:
return this.each(function() {
checkProgress(obj);
setup(obj);
});
So the event listening function has to be called before any event gets triggered, what of course makes perfect sense...
You need set event on your DOM model for instance:
$('#foo').bind('custom', function(event, param1, param2) {
alert('My trigger')
});
$('#foo').on('click', function(){ $(this).trigger('custom');});​
You DOM element should know when he should fire your trigger.
Please note that in your plugin you don't call any internal function - ONLY DECLARATION

jQuery Event when Validation Errors Corrected

I have buttons that trigger jQuery validation. If the validation fails, the button is faded to help draw attention away from the button to the validation messages.
$('#prev,#next').click(function (e)
{
var qform = $('form');
$.validator.unobtrusive.parse(qform);
if (qform.valid())
{
// Do stuff then submit the form
}
else
{
$('#prev').fadeTo(500, 0.6);
$('#next').fadeTo(500, 0.6);
}
That part works fine.
However, I would like to unfade the buttons once the invalid conditions have been cleared.
Is it possible to hook into jQuery Validation to get an appropriate event (without requiring the user to click a button)? How?
Update
Based on #Darin's answer, I have opened the following ticket with the jquery-validation project
https://github.com/jzaefferer/jquery-validation/issues/459
It might sound you strange but the jQuery.validate plugin doesn't have a global success handler. It does have a success handler but this one is invoked per-field basis. Take a look at the following thread which allows you to modify the plugin and add such handler. So here's how the plugin looks after the modification:
numberOfInvalids: function () {
/*
* Modification starts here...
* Nirmal R Poudyal aka nicholasnet
*/
if (this.objectLength(this.invalid) === 0) {
if (this.validTrack === false) {
if (this.settings.validHandler) {
this.settings.validHandler();
}
this.validTrack = true;
} else {
this.validTrack = false;
}
}
//End of modification
return this.objectLength(this.invalid);
},
and now it's trivial in your code to subscribe to this event:
$(function () {
$('form').data('validator').settings.validHandler = function () {
// the form is valid => do your fade ins here
};
});
By the way I see that you are calling the $.validator.unobtrusive.parse(qform); method which might overwrite the validator data attached to the form and kill the validHandler we have subscribed to. In this case after calling the .parse method you might need to reattach the validHandler as well (I haven't tested it but I feel it might be necessary).
I ran into a similar issue. If you are hesitant to change the source as I am, another option is to hook into the jQuery.fn.addClass method. jQuery Validate uses that method to add the class "valid" to the element whenever it is successfully validated.
(function () {
var originalAddClass = jQuery.fn.addClass;
jQuery.fn.addClass = function () {
var result = originalAddClass.apply(this, arguments);
if (arguments[0] == "valid") {
// Check if form is valid, and if it is fade in buttons.
// this contains the element validated.
}
return result;
};
})();
I found a much better solution, but I am not sure if it will work in your scenario because I do not now if the same options are available with the unobtrusive variant. But this is how i did it in the end with the standard variant.
$("#form").validate({
unhighlight: function (element) {
// Check if form is valid, and if it is fade in buttons.
}
});

Why are the jQuery functions only working the first time they're called?

There is a link that, when clicked, toggles between loading HTML into a div and emptying the div. When the div is clicked to load the html, I use the jQuery ajax load() function. When the text is loading, I want to display "Please wait...", so I tried using the jQuery ajaxStart() and ajaxStop() methods, but they only seemed to work the first time the load() function was called. So I switched to ajaxSend() and ajaxSuccess, but that also only seems to work the first time the load function is called. What's wrong?
HTML:
<p id="toggleDetail" class="link">Toggle Inspection Detail</p>
<p id="wait"></p>
<div id="inspectionDetail"></div>
jQuery:
$(
function(){
$('#toggleDetail').click(function(){
if($.trim($('#inspectionDetail').text()).length)
{
$('#inspectionDetail').empty();
}
else
{
$('#inspectionDetail').load('srInspectionDetailFiller.cfm');
}
});
}
);
$(
function(){
$('#wait').ajaxSend(function() {
$(this).text('Please wait...');
});
}
);
$(
function(){
$('#wait').ajaxSuccess(function() {
$(this).text('');
});
}
);
You should put up the 'Please wait...' message in your click function, then clear the message upon successful completion of your load:
$('#toggleDetail').click(function(){
if($.trim($('#inspectionDetail').text()).length)
{
$('#inspectionDetail').empty();
}
else
{
$('#wait').text('Please wait...');
$('#inspectionDetail').load('srInspectionDetailFiller.cfm', function() {
$('#wait').text('');
});
}
});
Edit: Although ajaxSend should technically work here, I don't recommend it. With ajaxSend, "All ajaxSend handlers are invoked, regardless of what Ajax request is to be sent". It seem overkill to me to hook all Ajax requests on the page which you're really only trying to deal with this single click.

Resources