On a recent project I was required to write some QUnit based tests for some jQuery widgets that I’d built. The goal was to try and test all of the functionality of the widget in isolation, however some aspects of the widget required animations to fire and complete before I could test the outcome.
QUnit was testing for the position of elements at the end of the animation, however as jQuery animations are done asynchronously (using setTimeout and/or setInterval I believe) the tests were failing as the animations were still in progress.
To resolve the issue we need to make jQuery stop animation in progress before making any assertions. To do this simply trigger the animation, followed by using the jQuery .stop()
function to cause all animations to complete immediately, before verifying the test conditions.
var $itemToAnimate = $("#item-to-animate"); $itemToAnimate.someAnimationCall(); //.slideDown, .animate etc. $itemToAnimate.stop(true, true); //some test condition here
The 2 arguments passed to stop clear all queued animations and make any active animations complete immediately.