Chai unittesting - expect(42).to.be.an('integer')

soerface picture soerface · May 11, 2014 · Viewed 16k times · Source

According to http://chaijs.com/api/bdd/#a, a/an can be used to check for the type of a variable.

.a(type)

@param{ String } type

@param{ String } message _optional_

The a and an assertions are aliases that can be used either as language chains or to assert a value's type.

However, I'm not able to check for the variable beeing an integer. The given examples, e.g. expect('1337').to.be.a('string'); work for me, but the following does not:

expect(42).to.be.an('integer');
expect(42).to.be.an('Integer');
expect(42).to.be.an('int');
expect(42).to.be.an('Int');

All of them are giving me the following error when running mocha:

Uncaught AssertionError: expected 42 to be an integer

How do I test with chai for a variable beeing an integer?

Answer

tleb picture tleb · Mar 4, 2016

A bit late, but for people coming from search engines, here is another solution:

var expect = require('chai').expect

expect(foo).to.be.a('number')
expect(foo % 1).to.equal(0)

The number check is required because of things such as true % 1 === 0 or null % 1 === 0.