繁体   English   中英

mocha-phantomjs用于回调函数的测试用例

[英]mocha-phantomjs test case for callback 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);
            }
        }
    });
}

我想测试这个功能,我选择了mocha-phantomjs 这是我的测试用例

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);
        }
    });
});

现在,通过提供错误"Invalid API Key"此测试应该失败。 但它过去了。 我想这是因为我在回调函数里面使用了断言,即handleData()

我正在使用mocha-phantomjs设置和chai断言库。

我搜索了教程和演示但是找不到任何东西。 我也试过mocha-phantomjs例子,但没有帮助我在这里发帖。

请告诉我如何在mocha-phantomjs测试回调函数。

您所描述的是异步测试但正在同步测试的典型症状。 解决方案是在测试中使用done回调:

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();
    }
});

当你将done参数添加到你给it的回调it ,你告诉Mocha测试是异步的,然后你必须在你的异步回调(这里是handleData )中调用它来告诉Mocha测试结束了。

否则,Mocha将运行给it的回调it并且不会等待handleData执行。 测试将立即结束,没有错误,所以摩卡会说它已经过去了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM