Vee6
Vee6

Reputation: 1577

Compare errors in Chai

I needed to implement my own error class in ES6 (with node v4):

class QueryObjectError {
    constructor (message) {
        this.message = message;
    }
}

I have a portion of code that throws said error type:

function myFunct () {
    throw new QueryObjectError('a message');
}

And I am using Mocha and Chai to test the the function throws the expected error with the expected message:

it('is a test', function (done) {
    var err = new QueryObjectError('abc');
    assert.throw(myFunct, err);
    done();
});

The test passes although the QueryObjectError objects have different messages and I want to test the case in which deep equality is checked. Any way to solve this with the given tools?

Upvotes: 0

Views: 1720

Answers (1)

Louis
Louis

Reputation: 151401

There are two salient issues with your code:

  1. You do not use assert.throw correctly. You should pass the constructor to the expected exception as the 2nd argument and a regular expression or a string as the 3rd argument. If the 3rd argument is a string, Chai will check that the string exist in the exception's message. If it is a regular expression, it will test whether the message is matched by the expression.

  2. Your exception should have a toString method that returns the message, otherwise Chai won't know how to check the message.

Here is an example showing a failure and a success:

import { assert } from "chai";

class QueryObjectError {
    constructor (message) {
        this.message = message;
    }

    toString() {
        return this.message;
    }
}

function myFunct () {
    throw new QueryObjectError('a message');
}

it('is a test', function () {
    assert.throw(myFunct, QueryObjectError, 'abc');
});

it('is another test', function () {
    assert.throw(myFunct, QueryObjectError, /^a message$/);
});

Upvotes: 1

Related Questions