简体   繁体   中英

Properly unit testing against NaN with mocha and assert

What is the proper way to test that function does not return or returns NaN. Consider:

 require('assert'); var functionUnderTest = function() { return NaN; } // mocha test for above function describe('Function returning NaN', function() { it('shall return NaN', function() { assert.equal(functionUnderTest(), NaN); // AssertionError: NaN == NaN assert.notEqual(functionUnderTest(), NaN); // No AssertionError }); }); 

I specifically want to test that function doesn't return NaN. I know that IEEE754 specifies that typeof NaN === "number" and it is not equal to itself (or any other number) and Javascript implements floats just as IEEE754 defines them.

But how to test that function returns or doesn't return NaN?

Why not using the isNaN function and do something like that:

require('assert');

var functionUnderTest = function() {
  return NaN;
}

// mocha test for above function
describe('Function returning NaN', function () {
  it('shall return NaN', function () {
    assert.equal(isNaN(functionUnderTest()), false); // AssertionError: NaN == NaN
    assert.notEqual(isNaN(functionUnderTest()), true); // No AssertionError
  });
});

If you are on the browser possibly you have to use the function like that: Number.isNaN(NaN)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM