【问题标题】:How can I chain multiple thens in mocha without using a done callback如何在不使用 done 回调的情况下在 mocha 中链接多个 then
【发布时间】:2015-08-02 11:45:48
【问题描述】:

在 mocha 中,您可以使用 done 回调来阻止 mocha 运行测试,直到您调用 done() 来表示所有承诺都已返回。在某些情况下,使用 done 是有问题的。有人告诉我,我可以返回一个与使用 done 具有基本相同效果的 promise。它将在期望结果成功或失败后解决(如果期望抛出测试将失败)。但是,当我开始将多个 then 链接在一起并导致测试通过时,即使期望失败。

按预期工作的完成示例(测试失败):

test('resync returns true upon success', function(done){
            Models.Asset.Load(this.testId).then(function(asset){
                asset.refresh().then(function(results){
                    expect(results !== null, "returns null, should return true");
                    expect(results.result === true, "does not return true");    
                    done();
                });
            });
        });

示例返回一个 promise 而不是使用 done 总是导致测试通过:

test('resync returns true upon success', function(){
            return Models.Asset.Load(this.testId).then(function(asset){
                asset.refresh().then(function(results){
                    expect(results !== null, "returns null, should return true");
                    expect(results.result === true, "does not return true");    
                });
            });
        });

我假设返回是返回第一个承诺的结果,这将始终为真,而不是返回应该是预期失败的链的最终结果。

参考这里是我之前的问题,其中向我解释了这种方法:

How can I pass mochas done callback function to another helper function

【问题讨论】:

    标签: javascript promise mocha.js


    【解决方案1】:

    您的测试失败了,因为 asset.refresh() 返回了一个承诺,但您正在返回它,并且默认返回 undefined 您的测试用例正在通过。 解决方案:

        test('resync returns true upon success', function(){
            return Models.Asset.Load(this.testId).then(function(asset){
                return asset.refresh().then(function(results){      // Line CHANGED, return added.
                    expect(results !== null, "returns null, should return true");
                    expect(results.result === true, "does not return true");    
                });
            });
        });
    

    替代方案:

        test('resync returns true upon success', function(){
            return Models.Asset.Load(this.testId).then(function(asset){
                return asset.refresh();
            }).then(function(results){
                expect(results !== null, "returns null, should return true");
                expect(results.result === true, "does not return true");    
            });;
        });
    

    【讨论】:

    • 啊,有道理。进行了更改,现在一切都按预期工作。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-06-16
    • 2012-04-14
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多