thebenedict thebenedict - 6 months ago 36
Javascript Question

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

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

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