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

thebenedict picture thebenedict · Oct 6, 2013 · Viewed 50k times · Source

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

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

with error "TypeError: Cannot read property 'should' of 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 get it working with "should"?

Answer

David Norman picture David Norman · Oct 6, 2013

This is one of the disadvantages of the should syntax. It works by adding the should property to all objects, but if a return value or variable value is undefined, there isn't a object to hold the property.

The documentation gives 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');
});