2

I'm trying to figure out how to check if a value is a positive number (bigger than zero) by using Chai. What I tried:

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

But it also works for -5 and 0. I also tried to change to integer but js does not have this type. How can I check it?

vesii
  • 2,760
  • 4
  • 25
  • 71

1 Answers1

3

You can use above(val) to check if a number is above a value.

This will make sure that the value is both a number and that it's above whatever value you want. In this case, since you want it to be a positive value, we'll use above(0).

If you want to also check if it's a whole number, you can use expect(val % 1).to.equal(0) as shown in 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>
Zachary Haber
  • 10,376
  • 1
  • 17
  • 31