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

扶醉桌前 提交于 2020-06-24 19:38:53

问题


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?


回答1:


JavaScript doesn't have a separate integer type.

Everything is a IEE 754 floating point number, which would of type number.




回答2:


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.




回答3:


This is also possible (at least whithin node):

expect(42).to.satisfy(Number.isInteger);

Here is a more advanced example:

expect({NUM: 1}).to.have.property('NUM').which.is.a('number').above(0).and.satisfy(Number.isInteger);



回答4:


I feel your pain, this is what I came up with:

var assert = require('chai').assert;

describe('Something', function() {

    it('should be an integer', function() {

        var result = iShouldReturnInt();

        assert.isNumber(result);

        var isInt = result % 1 === 0;
        assert(isInt, 'not an integer:' + result);
    });
});



回答5:


Depending on the browser/context you are running in there is also a function hanging off of Number that would be of some use.

var value = 42;
Number.isInteger(value).should.be.true;

It has not been adopted everywhere, but most of the places that matter (Chrome, FFox, Opera, Node)

More Info here




回答6:


Another [not optimal] solution (why not?!)

const actual = String(val).match(/^\d+$/);
expect(actual).to.be.an('array');
expect(actual).to.have.lengthOf(1);


来源:https://stackoverflow.com/questions/23597475/chai-unittesting-expect42-to-be-aninteger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!