Question

I'm using chaijs with mochajs for unit-testing. This is the doc of chaijs. http://chaijs.com/api/bdd/

according with the documentation, it can check if function throws an Exception. So, with this code:

var expect = require("chai").expect;
describe("Testing", function(){
    var fn = function(){ throw new Error("hello"); };
    //map testing
    describe("map", function(){
        it("should return error",function(){
            expect(fn()).to.not.throw("hello");
        });
    });
});

The test should say "Pass" riht ? it is expecting an Error, and function fn is giving it. But I'm getting this:

  11 passing (37ms)
  1 failing

  1) Testing map should return error:
     Error: hello
      at fn (/vagrant/projects/AD/tests/shared/functionalTest.js:13:29)
      at Context.<anonymous> (/vagrant/projects/AD/tests/shared/functionalTest.js:17:11)
      at Test.Runnable.run (/vagrant/projects/AD/node_modules/mocha/lib/runnable.js:211:32)
      at Runner.runTest (/vagrant/projects/AD/node_modules/mocha/lib/runner.js:372:10)
      at /vagrant/projects/AD/node_modules/mocha/lib/runner.js:448:12
      at next (/vagrant/projects/AD/node_modules/mocha/lib/runner.js:297:14)
      at /vagrant/projects/AD/node_modules/mocha/lib/runner.js:307:7
      at next (/vagrant/projects/AD/node_modules/mocha/lib/runner.js:245:23)
      at Object._onImmediate (/vagrant/projects/AD/node_modules/mocha/lib/runner.js:274:5)
      at processImmediate [as _immediateCallback] (timers.js:330:15)

I'm pretty sure I'm doing something stupid, or forgetting something stupid and i haven't noticed yet.

Can anyone see something that I cannot ? or any clue ? Thanks.

I'm using node.js v0.10.22 by the way.

Was it helpful?

Solution 2

As I supposed, I was missing something obvious !

instead of giving the function reference fn , I was giving function calling fn() !

this is the successful code

var expect = require("chai").expect;
describe("Testing", function(){
    var fn = function(){ throw new Error("hello"); };
    //map testing
    describe("map", function(){
        it("should return error",function(){
            expect(fn).to.throw("hello");
        });
    });
});

OTHER TIPS

For any one else having trouble testing Errors thrown from an object method:

The test

Wrap your method with an anonymous function call and it will work.

describe('myMath.sub()', function() {
   it('should handle bad data with exceptions', function(){
      var fn = function(){ myMath.sub('a',1); };
      expect(fn).to.throw("One or more values are not numbers");
   });
});

The object method

exports.sub = function(a,b) {
   var val = a - b;
   if ( isNaN(val)) {
      var err = new Error("One or more values are not numbers");
      throw err;
      return 0;
   } else {
      return val;
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top