mocha-phantomjs test case for callback function

纵饮孤独 提交于 2019-12-14 04:18:44

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/22837124/mocha-phantomjs-test-case-for-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!