Take the following Mongoose schema.
const userSchema = mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
minLength: 3
},
name: String,
passwordHash: String
})
const User = mongoose.model('User', userSchema)
By Mongoose official documentation You can make a custom error message for each schema path as following.
minLength: [3, 'username must be at least 3-character long']
In Node.js tests, you can easily test wrong cases as follows:
test('a user with too short username cannot be added into database', async () => {
try {
const user = new User({
username: 'x'
})
await user.save()
} catch (error) {
expect(error.username.message).toBe('username must be at least 3-character long')
}
})
For more readability though, I have a large validation error object, where each error is basically an object containing a message property and a code property:
const ERRORS = {
USER: {
USERNAME: {
USERNAME_TOO_SHORT: {
code: 'USERNAME_TOO_SHORT',
message: 'Username is too short.'
}
}
}
}
This way I'd only have to compare error codes in the tests not error messages:
expect(error.username.code).toBe(ERRORS.USER.USERNAME.USERNAME_TOO_SHORT.code)
The problem is mongoose does not allow "error objects" for each path:
minLength: [3, ERRORS.USER.USERNAME.USERNAME_TOO_SHORT]
This results in [object Object] as the message, which is not useful for testing.
I'm looking for a way to test mongoose validation errors based on an error code not message. As mentioned above mongoose won't allow error objects for a schema path, it only expects strings.