Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test for expected failure in Mocha

Tags:

Using Mocha, I am attempting to test whether a constructor throws an error. I haven't been able to do this using the expect syntax, so I'd like to do the following:

it('should throw exception when instantiated', function() {
  try {
    new ErrorThrowingObject();
    // Force the test to fail since error wasn't thrown
  }
  catch (error) {
   // Constructor threw Error, so test succeeded.
  }
}

Is this possible?

like image 887
bibs Avatar asked Feb 14 '13 16:02

bibs


People also ask

How do you fail a Mocha test?

fail("actual", "expected", "Error message"); }); Also, Mocha considers the test has failed if you call the done() function with a parameter. For example: it("should return empty set of tags", function(done) { done(new Error("Some error message here")); });

What is a test in Mocha?

Mocha is a testing library for Node. js, created to be a simple, extensible, and fast. It's used for unit and integration testing, and it's a great candidate for BDD (Behavior Driven Development).

What are pending tests in Mocha?

A pending test in many test framework is test that the runner decided to not run. Sometime it's because the test is flagged to be skipped. Sometime because the test is a just a placeholder for a TODO. For Mocha, the documentation says that a pending test is a test without any callback.


2 Answers

should.js

Using the should.js library with should.fail

var should = require('should')
it('should fail', function(done) {
  try {
      new ErrorThrowingObject();
      // Force the test to fail since error wasn't thrown
       should.fail('no error was thrown when it should have been')
  }
  catch (error) {
   // Constructor threw Error, so test succeeded.
   done();
  }
});

Alternative you can use the should throwError

(function(){
  throw new Error('failed to baz');
}).should.throwError(/^fail.*/)

Chai

And with chai using the throw api

var expect = require('chai').expect
it('should fail', function(done) {
  function throwsWithNoArgs() {
     var args {} // optional arguments here
     new ErrorThrowingObject(args)
  }
  expect(throwsWithNoArgs).to.throw
  done()
});
like image 134
Noah Avatar answered Oct 15 '22 23:10

Noah


You can try using Chai's throw construct. For example:

expect(Constructor).to.throw(Error);
like image 42
Mark Avatar answered Oct 15 '22 23:10

Mark