Last active
July 19, 2018 16:53
-
-
Save martypdx/2a169b71b0a8d81b49014d85e0aea9f5 to your computer and use it in GitHub Desktop.
Tests showing that objects in arrays are not all validated when one fails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require('assert'); | |
const mongoose = require('mongoose'); | |
const RequiredString = { type: String, required: true }; | |
const schema = new mongoose.Schema({ | |
name: RequiredString, | |
type: RequiredString, | |
colors: [{ | |
name: RequiredString, | |
hex: RequiredString | |
}], | |
address: { | |
city: RequiredString, | |
state: RequiredString | |
}, | |
numbers: [{ | |
type: Number, | |
min: 1, | |
max: 10 | |
}] | |
}); | |
const Model = mongoose.model('Model', schema); | |
it('all top-level fields validate and object properties', () => { | |
const model = new Model({}); | |
const { errors } = model.validateSync(); | |
const keys = Object.keys(errors).sort(); | |
assert.deepEqual(keys, [ | |
'address.city', | |
'address.state', | |
'name', | |
'type' | |
]); | |
}); | |
it('should validate all primitive members of array', () => { | |
const model = new Model({ | |
name: 'name', | |
type: 'type', | |
address: { city: 'Portland', state: 'OR' }, | |
numbers: [-2, 30] | |
}); | |
const { errors } = model.validateSync(); | |
const keys = Object.keys(errors).sort(); | |
assert.deepEqual(keys, ['numbers.0', 'numbers.1']); | |
}); | |
// fails | |
it('should validate all object members of array', () => { | |
const model = new Model({ | |
name: 'name', | |
type: 'type', | |
address: { city: 'Portland', state: 'OR' }, | |
colors: [ | |
{ name: 'steelblue' }, | |
{ hex: '#4682B4' } | |
] | |
}); | |
const { errors } = model.validateSync(); | |
const keys = Object.keys(errors).sort(); | |
assert.deepEqual(keys, ['colors.0.hex', 'colors.1.name']); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment