【问题标题】:Mocha and Chai test expect not to throw errorMocha 和 Chai 测试期望不会抛出错误
【发布时间】:2020-03-19 18:28:58
【问题描述】:

我正在用 Mocha 和 Chai 做一些测试

我有一些函数没有返回值,但如果有错误,它们会抛出错误

如果他们没有抛出错误,我想测试他们正在通过测试

例如

async function sum(a, b){
    Promise.resolve()
    .then()
    if(typeof(a) !== 'number')
        throw new Error('a should be a number')

    if(typeof(b) !== 'number')  
        throw new Error('b should be a number')

    console.log('the sum is ', a + b)

    return
}

然后我想测试它是否可以使用这样的东西

expect(sum(1, 2)).not.to.throw()

【问题讨论】:

  • Promise.resolve().then() 有什么用?
  • @slideshowp2,感谢您的评论。在实际代码中,我有更复杂的异步函数

标签: mocha.js chai


【解决方案1】:

解决这个问题的方法是使用chai-as-promise library

const chai = require('chai');
const chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
const expect = chai.expect;

expect(sum(1, 2)).to.eventually.not.be.rejectedWith(Error)

【讨论】:

    猜你喜欢
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 2017-03-24
    • 2019-06-28
    • 2018-08-26
    • 1970-01-01
    相关资源
    最近更新 更多