I was following the course material and learning the integration test. In the 10th video “Testing Invalid Inputs”, my test keep failing and I can not find out why.
My genre code has validation function like the sample code:
function validateGenre(genre){
const schema = {name: Joi.string().min(5).max(50).required()}
return Joi.validate(genre, schema)
}
exports.validate = validateGenre
And the genres module has the post block like this:
router.post('/', auth, async (req, res) => {
let {error} = validate(req.body)
if (error) res.status(400).send(error.details[0].message)
let genre = new Genre({name: req.body.name})
await genre.save()
res.send(genre)
})
The test code:
describe('POST /', () => {
it('should return 401 if client is not logged in', async () => {
const res = await request(server).post('/api/genres')
.send({name: 'genre1'})
expect(res.status).toBe(401)
})
it('should return 400 if genre is less than 5 characters', async () => {
const token = new User().generateAuthToken()
const res = await request(server).post('/api/genres')
.set('x-auth-token', token)
.send({name: '1234'})
expect(res.status).toBe(400)
})
})
And the message of failed test:
● /api/genres › POST / › should return 400 if genre is less than 5 characters
ValidationError: Genre validation failed: name: Path `name` (`1234`) is shorter than the minimum allowed length (5).
at model.Object.<anonymous>.Document.invalidate (node_modules/mongoose/lib/document.js:3123:32)
at node_modules/mongoose/lib/document.js:2911:17
at node_modules/mongoose/lib/schematype.js:1349:9
Looks like the test bypassed Joi validation in the genre module and went into mongoose schema validation, which is not right. However, if I do it in Postman, it return error code 400 just fine.
Can anyone help me figure out why the test is failing? Thanks a lot!