Chai + mocha,解决则测试成功,拒绝则失败

Posted

技术标签:

【中文标题】Chai + mocha,解决则测试成功,拒绝则失败【英文标题】:Chai + mocha, succeed in test if resolved, fail if rejected 【发布时间】:2019-10-25 13:52:13 【问题描述】:

我有一个返回承诺的函数。在我使用 chai 的测试文件中,我希望发生以下情况:

const result = sendSurveyDataToAnalytics(userId,eventType,eventTitle)

result.then(() => 
    Logger.info("Succeed in the test if we get here")
).catch(() => 
    Logger.info("Fail in the test if we get here")
);

代码解释了它。然后成功,捕获失败。使用可能期望或应该(已经安装 chai-as-promised)的正确方法是什么

【问题讨论】:

【参考方案1】:

如果您使用的是chai-as-promised

const result = sendSurveyDataToAnalytics(userId, eventType, eventTitle);

result.then(() => 
    Logger.info("Succeed in the test if we get here");
).catch(() => 
    Logger.info("Fail in the test if we get here");
);

it('resolves as promised', function() 
    return result.should.be.fulfilled;
);

// or:
it('rejects as promised', function() 
    return result.should.be.rejected;
);

【讨论】:

以上是关于Chai + mocha,解决则测试成功,拒绝则失败的主要内容,如果未能解决你的问题,请参考以下文章