How to assert not null?

Javascriptnode.jsmocha.js

Javascript Problem Overview


I'm very new in javascript testing, I would like to know how to assert not null in Mocha framework.

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

This is what worked for me (using Expect library with Mocha):

expect(myObject).toExist('Too bad when it does not.');

Solution 3 - Javascript

In case, you're using Chai in addition to Mocha:

assert.isNotNull(tea, 'great, time for tea!');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHosarView Question on Stackoverflow
Solution 1 - JavascriptAndre PenaView Answer on Stackoverflow
Solution 2 - JavascriptkatView Answer on Stackoverflow
Solution 3 - JavascriptFieryCatView Answer on Stackoverflow