【问题标题】:How to check if value is a positive number using Chai?如何使用 Chai 检查值是否为正数?
【发布时间】:2020-05-30 23:39:01
【问题描述】:

我试图弄清楚如何使用 Chai 来检查一个值是否为正数(大于零)。我尝试了什么:

expect(5).that.is.a('number');

但它也适用于 -50。我也试过改成integer,但是js没有这个类型。如何查看?

【问题讨论】:

    标签: javascript chai


    【解决方案1】:

    您可以使用above(val) 来检查一个数字是否大于某个值。

    这将确保该值既是数字​​又高于您想要的任何值。在这种情况下,由于您希望它是一个正值,我们将使用above(0)

    如果你还想检查它是否是一个整数,你可以使用expect(val % 1).to.equal(0),如Chai Unittesting - expect(42).to.be.an('integer')所示

    chai.expect(5).to.be.above(0)
    
    try {
      chai.expect(-5).to.be.above(0)
    } catch (error) {
      console.log(error.message);
    }
    try {
      chai.expect(0).to.be.above(0)
    } catch (error) {
      console.log(error.message);
    }
    
    try {
      chai.expect('5').to.be.above(0)
    } catch (error) {
      console.log(error.message);
    }
    
    try {
      let val = 2.5;
      chai.expect(val).to.be.above(0);
      chai.expect(val % 1,'to be a whole number').to.equal(0)
    } catch (error) {
      console.log(error.message);
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多