Search code examples
javascriptunit-testingasynchronouscallbackjs-test-driver

How to use asserts in callback function javascript


I have following code in test case:

flickrJson.prototype.testFlickrPhotoSearch = function() {
var wrongName = "googday";
var key = "3f807259749363aaa29c76012fa93945";
flickrPhotoSearch(wrongName, key, 1, handleData);

}

And handleData function:

var handleData = function(photoUrl)
{
    if (photoUrl.stat)
    {
        if (photoUrl.stat === "ok")
        {
            assertEquals(1,2);

        }
    }
}

I want to fail this test case. But when I write assert inside handleData function, it does not work.


Solution

  • For cases like this I have found the best way is to set a variable in the callback to some meaningful value (or values - perhaps one meaning ok, and another failure), then in the body of the test wait for the variable to be set (including a timeout so the test will fail if the variable is never set) and then once the test knows the variable is set - assert that it has the expected value.

    This is not a problem specific to JavaScript or any particular unit testing library; but it is a problem inherent in testing asynchronous code.