是否对Keystone.js中的必填字段,电子邮件字段和名称字段进行了验证?
以下是我的用户模型:
const keystone = require('keystone');
const Types = keystone.Field.Types;
const User = new keystone.List('User');
User.add({
name: { type: Types.Name, required: true, initial: true, index: true },
email: { type: Types.Email, required: true, initial: true, index: true, unique: true },
password: { type: Types.Password, initial: true, required: true },
}, 'Permissions', {
isAdmin: { type: Boolean, label: 'Can access Keystone', index: true },
});
// Provide access to Keystone
User.schema.virtual('canAccessKeystone').get(function () {
return this.isAdmin;
});
User.defaultColumns = 'name, email, isAdmin';
User.register();
某种单元测试。最后两个失败,因为错误没有抛出。
const User = keystone.list('User').model;
describe('User model', function () {
const newUser = {
name: {
first: 'Test',
last: 'Testov',
},
email: 'test@test.com',
password: 'test',
};
describe('validation', function () {
it('should reject a new user without email', function (done) {
const invalidUser = Object.assign({}, newUser);
delete invalidUser.email;
new User(invalidUser).validate((err) => {
assert.equal('Path `email` is required.', err.errors.email.message);
done();
});
});
it('should reject a new user without password', function (done) {
const invalidUser = Object.assign({}, newUser);
delete invalidUser.password;
new User(invalidUser).validate((err) => {
assert.equal('Path `password` is required.', err.errors.password.message);
done();
});
});
it('should reject a new user with invalid email', function (done) {
const invalidUser = Object.assign({}, newUser);
invalidUser.email = 'roflrofl';
new User(invalidUser).validate((err) => {
console.log(err);
assert.isOk(err);
done();
});
});
it('should reject a new user without name', function (done) {
const invalidUser = Object.assign({}, newUser);
invalidUser.name = { omg: 'wtf' };
new User(invalidUser).validate((err) => {
console.log(err);
assert.isOk(err);
done();
});
});
});
});
所以前两个单元测试通过正面,但最后两个不通过。为什么验证不起作用?
答案 0 :(得分:1)
这是因为validate
方法不是一个keystone方法,而是一个mongoose提供的方法。而且mongoose的验证远比keystone有限。
required: true
选项被传递给mongoose模式,这就是当您尝试将必填字段留空时它会抛出的原因。
validate
没有真正的keystone等价物,但只要您尝试保存文档,就会运行(mongoose + keystone)验证。
P.S。意识到太晚了,它与Keystone版本无关