4

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.

  • Are you sure `photoUrl.stat === "ok"` and the callback is being called? – Qantas 94 Heavy Jan 09 '14 at 12:30
  • yes we are in this condition. –  Jan 09 '14 at 12:32
  • I suggest using a test runner like Mocha, and reading its documentation for asynchronous tests. Otherwise, you're naturally required to make your minimal test harness (which I suppose you have) support asynchronous tests yourself. – Myrne Stol Jan 09 '14 at 12:40
  • Mocha is a different setup. Can we do this in js-test-driver? –  Jan 09 '14 at 12:44

1 Answers1

1

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.

verdammelt
  • 922
  • 10
  • 22