简体   繁体   English

执行查找查询时如何使猫鼬失败

[英]how can make mongoose fail when executing find query

Hi everyone I'm writing mocha unit tests for my server. 大家好,我正在为服务器编写Mocha单元测试。 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) : 下面不要与猫鼬的工作 ,至少现在是(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. 除了在find请求上设置适当的超时时间之外,关闭与猫鼬的连接是一种测试方法。

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. 更改请求maxTime或连接参数auto_reconnectsocketTimeoutMSconnectTimeoutMS似乎没有任何效果。 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 . 有关上一个stackoverflow主题的更多信息。

You can mock the mongoose connection and api to drive your test (raise errors...). 您可以模拟猫鼬连接和api来驱动测试(引发错误...)。

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. @ormaz @grégory-neut感谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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