Don*_*ker 7 unit-testing mongoose node.js vows expresso
有谁知道如何测试Mongoose Validations?
例如,我有以下Schema(作为示例):
var UserAccount = new Schema({
user_name : { type: String, required: true, lowercase: true, trim: true, index: { unique: true }, validate: [ validateEmail, "Email is not a valid email."] },
password : { type: String, required: true },
date_created : { type: Date, required: true, default: Date.now }
});
Run Code Online (Sandbox Code Playgroud)
该validateEmail方法被定义为这样的:
// Email Validator
function validateEmail (val) {
return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(val);
}
Run Code Online (Sandbox Code Playgroud)
我想测试验证.最终的结果是我希望能够测试验证并根据发生的事情,然后我可以编写其他测试来测试这些代码片段之间的交互.示例:用户尝试使用与所用用户名相同的用户名进行注册(电子邮件已在使用中).我需要一个我可以实际拦截的测试,或者看到验证工作没有达到DB.我不想在这些测试中击中Mongo.这些应该是UNIT测试而不是集成测试.:)
谢谢!
Cra*_*gor 11
我最近遇到了同样的问题.
首先,我建议自己测试验证器.只需将它们移动到单独的文件并导出您拥有的验证功能即可.
这样可以轻松地将模型拆分为单独的文件,因为您可以跨不同模型共享这些验证器.
以下是自行测试验证器的示例:
// validators.js
exports.validatePresenceOf = function(value){ ... }
exports.validateEmail = function(value){ ... }
Run Code Online (Sandbox Code Playgroud)
这是一个示例测试(使用mocha + should):
// validators.tests.js
var validator = require('./validators')
// Example test
describe("validateEmail", function(){
it("should return false when invalid email", function(){
validator.validateEmail("asdsa").should.equal(false)
})
})
Run Code Online (Sandbox Code Playgroud)
现在更难的部分:)
要在不访问数据库的情况下测试模型是否有效,可以在模型上直接调用验证函数.
这是我目前如何做的一个例子:
describe("validating user", function(){
it("should have errors when email is invalid", function(){
var user = new User();
user.email = "bad email!!"
user.validate(function(err){
err.errors.email.type.should.equal("Email is invalid")
})
})
it("should have no errors when email is valid", function(){
var user = new User();
user.email = "test123@email.com"
user.validate(function(err){
assert.equal(err, null)
})
})
})
Run Code Online (Sandbox Code Playgroud)
验证器回调获取一个错误对象,看起来像这样:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ email:
{ message: 'Validator "Email is invalid" failed for path email',
name: 'ValidatorError',
path: 'email',
type: 'Email is invalid'
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还是nodeJS和mongoose的新手,但这就是我测试我的模型+验证器的方法,到目前为止看起来效果还算不错.
| 归档时间: |
|
| 查看次数: |
2819 次 |
| 最近记录: |