2000ms的超时超过了摩卡

5 javascript unit-testing callback mocha.js mocha-phantomjs

我有两个测试用例,即它("应该通过...")..和它("应该失败...")..,当我测试它时,它给出超过2000毫秒的超时错误.

describe("flickrphotoSearch", function () {
it("should pass with correct inputs", function (done) {
    flickrApplication.flickrPhotoSearch("hello", "flickr_user_Key", 1, handleData);
    function handleData(photoUrl, done) {
        this.setTimeout(1500);
        assert.isString(photoUrl.toString(), 'not a string');
        setTimeout(done, 1000);
    };
});
it("should fail with wrong key", function (callingDone) {
    flickrApplication.flickrPhotoSearch("hello", "wrong key", 1, handleData);
    function handleData(photoUrl, done) {
        this.setTimeout(1500);
        assert.equal(photoUrl.stat, "ok", photoUrl.message);
        setTimeout(done, 1000);
    };
});
});
Run Code Online (Sandbox Code Playgroud)

对于第一次测试我超时超时错误,但第二次运行良好.请告诉我我错在哪里.

Est*_*ban 1

这有两个部分。首先,当您尝试设置测试超时时,您没有调用setTimeout正确对象上的方法。这是由于关闭:

describe("flickrphotoSearch", function () {
it("should pass with correct inputs", function (done) {
    # 'this' is the mocha test here.
    flickrApplication.flickrPhotoSearch("hello", "flickr_user_Key", 1, handleData);
    function handleData(photoUrl, done) {
        this.setTimeout(1500); # What's 'this' here? The global object.
        assert.isString(photoUrl.toString(), 'not a string');
        setTimeout(done, 1000);
    };
});
Run Code Online (Sandbox Code Playgroud)

handleData被调用时,this不绑定到任何东西,因为函数是单独调用的,而不是作为对象方法调用。有关闭包和this绑定的更多信息,请参阅这篇 jQuery 学习中心文章。您可以通过执行以下操作来纠正该问题:

flickrApplication.flickrPhotoSearch("hello", "flickr_user_Key", 1, handleData.bind(this));
Run Code Online (Sandbox Code Playgroud)

然而,在这种情况下,您也可以将其移到this.setTimeout(1500)handleData之外,并且它会产生相同的效果。

另一部分是,如果超过 2000 毫秒超时,您的 1500 毫秒限制也将被超过。此外,这是不确定的,因为它取决于 flickr API 响应时间。

我的建议是,如果这是一个单元测试(与集成测试相反),则模拟 flickr API。