I am trying to validate using supertest
that the response returned by a REST endpoint contains the validation error of moongose
validation which looks like below
errors: Object {
firstName: Object {
kind: 'required',
message: 'Path `firstName` is required.',
name: 'ValidatorError',
path: 'firstName',
properties: Object {
message: 'Path `{PATH}` is required.',
path: 'firstName',
type: 'required'
},
}
I am writing following test
it('should return well formatted error response when first name is missing', function(done){
var user = {lastName:"Ranger", email:"dan.ranger@gmail.com"};
request(app)
.post('/api/user')
.send(user)
.end(function(err, res){
res.body.should.have.property("path", "firstName");
done();
});
});
But I am getting following error
AssertionError: expected Object {
errors: Object {
firstName: Object {
kind: 'required',
message: 'Path `firstName` is required.',
name: 'ValidatorError',
path: 'firstName',
properties: Object {
message: 'Path `{PATH}` is required.',
path: 'firstName',
type: 'required'
},
}
},
message: 'User validation failed',
name: 'ValidationError',
} to have property path
at Test.<anonymous> (test/userTests.js:23:25)
at net.js:1276:10
How can I write such asserts?
You are asserting that res.body
has property 'path'
, however res.body is the parent object which only contains the properties errors
, message
, and name
.
You could test for these properties, or you can access the nested error object as follows:
.end(function(err, res){
res.body.errors.firstName.should.have.property("path")
done();
});
It is likely more convenient just to test properties on the parent object, as this should prove sufficient.