2

Hi everyone I'm writing mocha unit tests for my server. How can I get error for mongoose find query. I've tried close the connection before execute but there's nothing firing.

User.find({}, (err, result) => {
    if (err) {
        // I want to get here
    }
    return done(result);
});
S.Polat
  • 71
  • 8

3 Answers3

2

The following DO NOT WORK with mongoose, at least for now (5.0.17) :


Closing the connection to mongoose is a way to test it, in addition to a proper timeout to set on the find request.

const request = User.find({});

request.maxTime(1000);

request.exec()
       .then(...)
       .catch(...);

or

User.find({}, { maxTimeMS: 1000 }, (err, result) => {
    if (err) {
        // I want to get here
    }

    return done(result);
});

EDIT after further researches :


After trying it myself, it seems that I never get an error from the request.

Changing request maxTime or connection parameters auto_reconnect, socketTimeoutMS, and connectTimeoutMS do not seems to have any effect. The request still hang.

I've found this stack overflow answer saying that all request are queued when mongoose is disconnected from the database. So we won't get any timeout from there.

A soluce I can recommand and that I use on my own project for another reason would be to wrap the mongoose request into a class of my own. So I could check and throw an error myself in case of disconnected database.

Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
  • it's not working. There's no error for your code. @grégory-neut – S.Polat May 07 '18 at 13:47
  • What connection argument do you have? Especially `auto_reconnect`, `socketTimeoutMS` and `connectTimeoutMS`. Didn't tested but it should totally work – Orelsanpls May 07 '18 at 14:24
  • there's no special arg. for connection. here is my connection setup 'mongoose.connect(url);" – S.Polat May 07 '18 at 14:27
1

In my opinion, the best way to test your error handling is to use mock. More information in this previous stackoverflow topic.

You can mock the mongoose connection and api to drive your test (raise errors...).

Libraries:

Ormaz
  • 46
  • 5
0

I solved it like below. Here is the solution.

User = sinon.stub(User.prototype, 'find');
User.yields(new Error('An error occured'), undefined);

By this code it will return error. @ormaz @grégory-neut Thanks for the help.

S.Polat
  • 71
  • 8