Chai: how to test for undefined with the syntax 'should'

Based on this tutorial on testing angularjs app with chai, I want to add a test for undefined value using the "should" style. This fails:

it ('cannot play outside the board', function() { scope.play(10).should.be.undefined; }); 

with the error "TypeError: Unable to read the 'should' property from undefined", but the test passes with the "expect" style:

 it ('cannot play outside the board', function() { chai.expect(scope.play(10)).to.be.undefined; }); 

How can I make it work with a must?

+69
javascript angularjs testing chai
Oct 06 '13 at 13:02
source share
9 answers

This is one of the shortcomings of the if syntax. It works by adding the all property to all objects, but if the return value or the value of the variable is undefined, the object has no property.

The documentation provides some workarounds, for example:

 var should = require('chai').should(); db.get(1234, function (err, doc) { should.not.exist(err); should.exist(doc); doc.should.be.an('object'); }); 
+62
Oct 06 '13 at
source share
 should.equal(testedValue, undefined); 

as stated in the chai documentation

+36
May 20 '14 at 11:59
source share
 (typeof scope.play(10)).should.equal('undefined'); 
+15
Jun 23 '14 at 3:43
source share

Test for undefined

 var should = require('should'); ... should(scope.play(10)).be.undefined; 

Check null

 var should = require('should'); ... should(scope.play(10)).be.null; 

Falsity test, i.e. considered false in the conditions

 var should = require('should'); ... should(scope.play(10)).not.be.ok; 
+14
Jun 02 '15 at 12:51 on
source share

I struggled to write an if statement for undefined tests. Does not work.

 target.should.be.undefined(); 

I found the following solutions.

 (target === undefined).should.be.true() 

if he can also write it as a type check

 (typeof target).should.be.equal('undefined'); 

Not sure if this is correct, but it works.

According to a ghost post on github

+5
Jun 08 '16 at 23:51
source share

Try the following:

 it ('cannot play outside the board', function() { expect(scope.play(10)).to.be.undefined; // undefined expect(scope.play(10)).to.not.be.undefined; // or not }); 
+3
Oct 06 '13 at 13:26
source share

@ David-norman's answer is correct according to the documentation, I had a few setup problems and chose the following instead.

(typeof scope.play (10)). should.be.undefined;

+1
Sep 04 '14 at 9:32
source share

You can wrap the result of your function in should() and test the type "undefined":

 it ('cannot play outside the board', function() { should(scope.play(10)).be.type('undefined'); }); 
0
Feb 20 '14 at 21:46
source share

Remember the combination of the have and not keywords:

 const chai = require('chai'); chai.should(); // ... userData.should.not.have.property('passwordHash'); 
0
Nov 30 '17 at 17:34
source share



All Articles