I'm very new in javascript testing, I would like to know how to assert not null in Mocha framework.
Asked
Active
Viewed 1.1e+01k times
3 Answers
132
Mocha supports any assertion library you want. You can take a look at how it deals with assertions here: http://mochajs.org/#assertions. I don't know which one you want to use.
Considering you are using Chai, which is pretty popular, here are some options:
Consider "foo" to be the target variable you want to test
Assert
var assert = chai.assert;
assert(foo) // will pass for any truthy value (!= null,!= undefined,!= '',!= 0)
// or
assert(foo != null)
// or
assert.notEqual(foo, null);
In case you want to use assert
, you don't even need Chai. Just use it. Node supports it natively: https://nodejs.org/api/assert.html#assert_assert
Should
var should = require('chai').should();
should.exist(foo); // will pass for not null and not undefined
// or
should.not.equal(foo, null);
Expect
var expect = chai.expect;
expect(foo).to.not.equal(null);
// or
expect(foo).to.not.be.null;
PS: Unrelated but on Jest there is a toBeNull
function. You can do expect(foo).not.toBeNull();
or expect(foo).not.toBe(null);

Andre Pena
- 56,650
- 48
- 196
- 243
-
2thanks cause the freakin docs unless I'm missing it don't state you can just do assert(something) for the null & undefined check at the same time. – PositiveGuy Jul 11 '15 at 21:36
-
Based on Chai's documentation: "Just because you can negate any assertion with .not doesn’t mean you should. With great power comes great responsibility. It’s often best to assert that the one expected output was produced, rather than asserting that one of countless unexpected outputs wasn’t produced. See individual assertions for specific guidance." – Wayne Smallman Dec 27 '22 at 13:57
3
This is what worked for me (using Expect library with Mocha):
expect(myObject).toExist('Too bad when it does not.');

kat
- 577
- 4
- 7
-
1Expect belongs to Facebook. Me personally I don't want a FB npm package with access to my filesystem. – Josep Alsina Jul 23 '21 at 07:28
3
In case, you're using Chai in addition to Mocha:
assert.isNotNull(tea, 'great, time for tea!');

FieryCat
- 1,875
- 18
- 28