javascriptunit-testingcallbackmocha.jsmocha-phantomjs

mocha-phantomjs test case for callback function


I have a module in which I have this function

flickrPhotoSearch: function (searchByName, flickrUserKey, numberOfImages, callbackData) {
    return $.ajax({
        url: commonConstants.BASE_URL + "flickr.photos.search&api_key=" + flickrUserKey + "&tags=" + searchByName + "&format=json&jsoncallback=?",
        dataType: 'json',
        async: true,
        success: function (jsonData) {
            if (jsonData.stat === commonConstants.JSON_SUCCESS) {
                if (jsonData.photos['photo'].length < commonConstants.DATA_LENGTH) {
                    callbackData(jsonData);
                } else {
                    var flickrImage = flickrApplication.jsonToImage(jsonData, numberOfImages);
                    callbackData(flickrImage);
                }
            } else {
                callbackData(jsonData);
            }
        }
    });
}

I want to test this function and I choose mocha-phantomjs for it. And this is my test case

describe("flickrphotoSearch", function () {
    it("should fail with wrong key", function () {
        flickrApplication.flickrPhotoSearch(testConstant.CORRECT_NAME, testConstant.WRONG_KEY, testConstant.CONSTANT_ONE, handleData);
        function handleData (photoUrl) {
            assert.equals(photourl.stat, "pass", photoUrl.message);
        }
    });
});

Now this test should fail by giving error "Invalid API Key". But It got passed. I think this is because I used assertion inside callback function i.e. handleData().

I am using mocha-phantomjs setup and chai assertion library.

I searched for tutorials and demos but coudn't find any. Also I tried mocha-phantomjs examples but with no help I am posting here.

Please tell me how to test callback function in mocha-phantomjs.


Solution

  • What you describe is the typical symptom for a test that is asynchronous but is being tested synchronously. The solution is to use the done callback in your test:

    it("should fail with wrong key", function (done) {
        flickrApplication.flickrPhotoSearch(testConstant.CORRECT_NAME, testConstant.WRONG_KEY, testConstant.CONSTANT_ONE, handleData);
        function handleData (photoUrl) {
            assert.equals(photourl.stat, "pass", photoUrl.message);
            done();
        }
    });
    

    When you add the done argument to the callback you give to it, you tell Mocha that the test is asynchronous and then you must call it in your asynchronous callback (handleData here) to tell Mocha that the test is over.

    Otherwise, Mocha will run the callback given to it and won't wait for handleData to execute. The test will end right away, without errors, so Mocha will say it has passed.