chai: Throw custom error (ES6)

Given a custom error:

export default class DummyError extends Error {
    /**
     * @param {string} [message='']
     */
    constructor(message = '') {
        super(message);

        this.name = 'DummyError';
        this.message = message;

        if (Error.hasOwnProperty('captureStackTrace')) {
            Error.captureStackTrace(this, this.constructor);
        }

        this.stack = (new Error(message)).stack;
    }
}

And the following function:

function throwDummyError() {
    throw new DummyError();
}

The following doesn’t work:

assert.throw(throwDummyError, DummyError);

And instead is throwing:

AssertionError: expected [Function: DummyError] to throw 'DummyError' but 'my error message' was thrown

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 1
  • Comments: 24 (13 by maintainers)

Commits related to this issue

Most upvoted comments

Thanks @meeber, it seems that this is a known issue. I’ll just have to do some workarounds to get this working.

I think I might have a similar issue.

I have the following custom error (Typescript code below):

const message: string = `error message`;

export class InvalidReferenceFormatError extends Error {
    constructor() {
        super(message);
        this.name = "InvalidReferenceFormatError";
        this.stack = (<any> new Error()).stack;
    }
}

And the assertion:

expect(() => { throw new InvalidReferenceFormatError() }).to.throw(InvalidReferenceFormatError);

This results in: AssertionError: expected [Function] to throw 'InvalidReferenceFormatError' but 'InvalidReferenceFormatError: error message' was thrown

Is a message mandatory for custom errors? Using chai version 3.5.0.

Hi @lucasfcosta, I’ll try to take a look at it again during the weekend 😃