user6468132
user6468132

Reputation: 403

Error handling in mocha unit tests

I have mocha tests. I will simplify as possible as I can. I wonder how should I handle the errors in mocha tests. For example, if there is an error in getName, what should I do? How can I throw an error? Or should I use done(error) as;

 it('trial', function(done) {
    getName(function (name, err) {
        if(err){
            done(err); //what should I do here? 
        }else{
            console.log(name);
        }
    });
});

Upvotes: 1

Views: 4796

Answers (1)

DrakaSAN
DrakaSAN

Reputation: 7873

If doneis called with a argument other than undefined, the test will fail and be reported as such. Other test will still be executed.

It allow you to test for success, but also for error:

it('succeed', (done) => {
    myFunc('success', (err, res) => {
        if(err) {
            done(err);
        } else if(res !== 'expected') {
            done('Wrong result ' + res);
        } else {
            done();
        }
    });
});

it('fail with error 404', (done) => {
    myFunc('fail', (err, res) => {
        if(err) {
            if(err === 404) {
                done();
            } else {
                done('Error was expected to be 404, got ' + err);
            }
        } else {
            done('Was expected to fail, got result ' + res + ' and no error');
        }
    });
});

it('succeed', (done) => {
    try {
        var res = myFuncSync('succeed');
    } catch(err) {
        done(err);
    }
    done();
});

it('fail with error 404', (done) => {
    try {
        var res = myFuncSync('succeed');
    } catch(err) {
        if(err === 404) {
            done();
        } else {
            done('Error was expected to be 404, got ' + err);
        }
    }
    done('Was expected to fail, got result ' + res + ' and no error');
});

Upvotes: 3

Related Questions