Question

I was trying to write some test cases for my js functions, but I am facing an irritating issue.

In my script there is a code section like:

$("idOfTheDiv").fadeOut('fast');

or:

$("idOfTheDiv").fadeTo('fast', 1);

which works fine on my pages.

The problem came when I had wanted to write some js-test-driver unit test cases. When I want to verify the fadeTo function:

...

assertTrue($("#idOfTheDiv").css("opacity") == "0");

...

then it fails.

The reason could be that this is an animation and when I try to verify, it does not finish the animation.

Could somebody know a way to be able to test jQuery animate functions in js-test-driver?

Was it helpful?

Solution

To test asynchronous behaviour you need to use the AsyncTestCase from js-test-driver.

Try this:

FadeTest = AsyncTestCase("FadeTest", {

testFadeOut : function(queue) {
    // add HTML to your Test
    /*:DOC += <div id="idOfTheDiv"><p>foo</p></div>*/

    var animationComplete = false;

    queue.call('prepare test', function(callbacks) {
        var onAnimationComplete = callbacks.add(function() {
            animationComplete = true;
        });

        $("#idOfTheDiv").fadeOut('fast', onAnimationComplete);
    });

    // The async test will wait until the onAnimationComplete function has been called.
    // So the following part is executed when the animation is done.
    queue.call('assertion', function() {
       assertTrue(animationComplete);
       // Now you can check the opacity of the div
       assertEquals(0, $("#idOfTheDiv").css("opacity")); 
    });

}

});

Note: I haven't tried the code myself. Hope there are no typos. ;)

Edit: If the function you want to test does not have a callback functionality you can add it using AOP. The procedure is:

  • Add a after() callback to the function you want to test (as in this jsfiddle).
  • Register the after() function in the callbacks object of the queue.
  • In the next queue-step you can then make assertions that should be true after your method has completed.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top