简体   繁体   English

摩卡测试失败,因为这在猫鼬预验证钩子模型中未定义(即使没有箭头功能)

[英]mocha test fail because this is undefined in mongoose pre validate hooks model (even without arrow function)

I'm testing a post request that basically registers users to db. 我正在测试一个基本上将用户注册到db的发布请求。 my mocha test fails because this is undefined when the pre validate hooks is triggered. 我的Mocha测试失败,因为触发验证钩子时未定义。 I'm already using a normal function instead of an arrow function. 我已经在使用普通功能而不是箭头功能。 It works perfectly in postman/insomnia . 它在postman/insomnia非常有效。 the problem occurs if I'm testing it through mocha. 如果我通过摩卡咖啡进行测试,则会出现问题。

userSchema.pre('validate', function(next) {

    if (this.password.split(' ').length > 1) {
        next(new Error('password can not contain a white space'));
    } else {
        next();
    }
});

For access to this it should be separate function 要访问它,它应该是单独的功能

function preValidateFunction(next) {
    if (this.password.split(' ').length > 1) {
        next(new Error('password can not contain a white space'));
    } else {
        next();
    }
}

userSchema.pre('validate', preValidateFunction);

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

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