【问题标题】:Trouble testing mongoose async hook with mocha使用 mocha 测试猫鼬异步钩子时遇到问题
【发布时间】:2021-03-01 01:56:21
【问题描述】:

我正在尝试对预验证猫鼬模型方法进行单元测试。

这是模型部分:

export const hashPassword = async function () {
  console.log('test1');
  return Promise.resolve();
};

userSchema.pre('validate', hashPassword);

这里是单元测试部分

it('hash password pre save hook', async () => {
    const user = new User({
      email: 'email@email.com',
      firstName: 'firstName',
      lastName: 'lastName',
      userName: 'userName',
      password: 'password',
    });

    await user.validate();
    console.log('test2');
  });

最后,我收到的错误消息

错误:超过 2000 毫秒的超时。对于异步测试和钩子,确保 “完成()”被调用;如果返回一个 Promise,请确保它解析。

所以方法中的console.log被触发了,但不是第二个。我将代码简化为最简单的逻辑,我仍然无法使其工作。

我检查并且我是 100% 肯定的,它来自钩子本身。不是来自mocha,不是来自hash函数,是来自mongoose hook。

PS:是的,我试过增加timeOut没有成功

【问题讨论】:

    标签: node.js unit-testing mongoose mocha.js


    【解决方案1】:

    由于您的测试包含异步代码,因此您需要确保代码在使用测试验证之前完成其功能。

    从 Mocha 文档,测试异步代码:

    通过给 it() 添加一个参数(通常命名为 done)到一个测试回调中,Mocha 会知道它应该等待这个函数被调用来完成测试。此回调接受错误实例(或其子类)或虚假值;其他任何内容都是无效使用并引发错误(通常会导致测试失败)。

    describe('User', function() {
      describe('#save()', function() {
        it('should save without error', function(done) {
          var user = new User('Luna');
          user.save(function(err) {
            if (err) done(err);
            else done();
          });
        });
      });
    });
    

    或者,直接使用 done() 回调(它将处理错误参数,如果存在):

    describe('User', function() {
      describe('#save()', function() {
        it('should save without error', function(done) {
          var user = new User('Luna');
          user.save(done);
        });
      });
    });
    

    另外,如果从未调用过done(),则测试将失败(出现超时错误)

    了解更多,请访问:https://mochajs.org/#asynchronous-code

    【讨论】:

    • 抱歉,这不是解决方案。正如我所指定的,我从不退出散列函数,因此,我从不触发it 中的done。而且我还尝试将done 传递给钩子函数,但没有成功。
    【解决方案2】:

    好的,睡了之后,我找到了这个问题的原因。我在模式中有一个异步验证器,它执行对数据库的请求。我没有给它存根,所以它触发了超时。

    这是负责的部分代码:

    const userSchema = new Schema({
      email: {
        type: String,
        required: true,
        unique: true,
        validate: {
          async validator(email): Promise<boolean> {
            const isNonUniqueEmail = await mongoose.model('user').exists({ email });
            return !isNonUniqueEmail;
          },
          message: 'nonUniqEmail',
        },
      },
    });
    

    我忘记了第一个堆栈溢出规则:在互联网上询问之前先解决你的错误。

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 2017-01-29
      • 2016-09-18
      • 2020-02-23
      • 1970-01-01
      • 2018-03-04
      • 2019-11-12
      • 2020-10-16
      • 2019-05-04
      相关资源
      最近更新 更多