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?
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")); });
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).
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.
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.*/)
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()
});
You can try using Chai's throw
construct. For example:
expect(Constructor).to.throw(Error);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With