Mocha/Chai Expect.To.Throw Not Catching Thrown Errors

Mocha / Chai expect.to.throw not catching thrown errors

You have to pass a function to expect. Like this:

expect(model.get.bind(model, 'z')).to.throw('Property does not exist in model schema.');
expect(model.get.bind(model, 'z')).to.throw(new Error('Property does not exist in model schema.'));

The way you are doing it, you are passing to expect the result of calling model.get('z'). But to test whether something is thrown, you have to pass a function to expect, which expect will call itself. The bind method used above creates a new function which when called will call model.get with this set to the value of model and the first argument set to 'z'.

A good explanation of bind can be found here.

Mocha/Chai unable to catch error object from a function

The problem is that, you're trying to test if an async function throws an error. Async functions are just normal functions which, internally, convert into promises. Promises do not throw, but they do reject. You have to handle their errors using .catch() or catch() {} in an async parent function.

A way to handle this in Chai is to use the chai-as-promised library, which is a plugin to Chai and enables handling of Promise-based checks.

Here is an example of what you should be doing:

const course = createCourse(test_course, user_notVolunteer.id);
await expect(course).to.eventually.be.rejectedWith("User must be a volunteer");

Mocha/Chai: testing thrown Errors with error message

You are correct that your assertion is failing because Chai .throw is comparing error objects by strict equality. From the spec:

When one argument is provided, and it’s an error instance, .throw invokes the target function and asserts that an error is thrown that’s strictly (===) equal to that error instance.

The same spec explains:

When two arguments are provided, and the first is an error instance or constructor, and the second is a string or regular expression, .throw invokes the function and asserts that an error is thrown that fulfills both conditions as described above.

where

.throw invokes the target function and asserts that an error is thrown with a message that contains that string.

So the way to test the desired behavior is using two arguments like this:

expect(Person.getPerson.bind(Person, id)).to.throw(Error, `Person ${id} not found`);

test for error thrown in node.js using mocha chai

You are passing a new instance of TypeError to the expect() function, which means it will expect your which_min() function to throw that exact error instance (but it won't do that, it will throw another instance of the same error type with the same error message).

Try just passing the error string instead, so:

var assert = require('chai').assert;
var expect = require('chai').expect;
describe('#which_min()', function() {
context('with incorrect arguments', function() {
it('errorTest', function() {
expect(function(){utils.which_min();}).to.throw("Cannot read property 'length' of undefined")
})
})
})

In that case, Chai will expect any error type with the same error message to be thrown.

You could also choose to assert that the error is a TypeError like this:

var assert = require('chai').assert;
var expect = require('chai').expect;
describe('#which_min()', function() {
context('with incorrect arguments', function() {
it('errorTest', function() {
expect(function(){utils.which_min();}).to.throw(TypeError)
})
})
})

But then you aren't asserting that the error message is exactly what you expect.

Refer to the official Chai documentation here for more info:
https://www.chaijs.com/api/bdd/#method_throw

EDIT:

As @Sree.Bh mentions, you can also pass both the expected type of the error and the expected error message to the throw() assertion, like so:

var assert = require('chai').assert;
var expect = require('chai').expect;
describe('#which_min()', function() {
context('with incorrect arguments', function() {
it('errorTest', function() {
expect(function(){utils.which_min();}).to.throw(TypeError, "Cannot read property 'length' of undefined")
})
})
})

Mocha and Chai test expect not to throw error

The way to solve this was to use chai-as-promise library

const chai = require('chai');
const chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
const expect = chai.expect;

expect(sum(1, 2)).to.eventually.not.be.rejectedWith(Error)

Chai - expect function to throw error

With the caveat that I'm no Chai expert, the construct you have:

expect(subject.formatPostcodeStatus(status)).to.throw(Error);

cannot possibly handle the thrown exception before the Chai framework gets around to seeing your .to.throw() chain. The code above calls the function before the call to expect() is made, so the exception happens too soon.

Instead, you should pass a function to expect():

expect(function() { subject.formatPostCodeStatus(status); })
.to.throw(Error);

That way, the framework can invoke the function after it's prepared for the exception.

Chai expect .to.throw(Error) not working as expected

Your question is a duplicate of Mocha / Chai expect.to.throw not catching thrown errors

The most straightforward way to fix your issue would be to make the call to your code from an arrow function:

it.only('should throw an error if the transcription cannot happen', () => {   
expect(() => TranscriptLib.myFunc({ data }, '1')).to.throw(Error)
})

As the answers on the other question show you can also use .bind to create a new function, and so on and so forth.



Related Topics



Leave a reply



Submit