简体   繁体   中英

how can make mongoose fail when executing find query

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);
});

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM