Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert not null?

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

like image 673
Hosar Avatar asked Apr 06 '15 03:04

Hosar


People also ask

How do you assert an object to not be null?

The assertNotNull() method means "a passed parameter must not be null ": if it is null then the test case fails. The assertNull() method means "a passed parameter must be null ": if it is not null then the test case fails. Show activity on this post. assertNotNull asserts that the object is not null.

IS NOT null assertion?

NotNull(Object, String) Verifies that the object that is passed in is not equal to null If the object is null then an AssertionException is thrown.

How do you assert for null?

Verifies that the object that is passed in is equal to null If the object is not null null then an AssertionException is thrown. Verifies that the object that is passed in is equal to null If the object is not null then an AssertionException is thrown.

What does assert != null do in Java?

Adding an error message A lesser-known feature of assert is that you can append an error message. For example: assert o != null : "o is null"; This error message is then passed to the AssertionError constructor and ​printed along with the stack trace.


2 Answers

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

like image 132
André Pena Avatar answered Sep 23 '22 06:09

André Pena


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

expect(myObject).toExist('Too bad when it does not.'); 
like image 20
kat Avatar answered Sep 26 '22 06:09

kat