I am trying to set up a unit test for a POST function of my express app.
I have the following simple Mongoose schema with two fields and one of them is required.
When I conduct the mocha test with the validation/required-field turned off, the test is fine, however when the required is set to true, the test failes with the following error:
Uncaught: No listeners detected,
throwing. Consider adding an error listener to your connection.
ValidationError: Path 'title' is required
Any ideas? As you can see, I definitely have satisfied the schema requirements and have included the title field.
Here is my test below:, interestingly, the first test seems to work fine, it's only when I try to post that it generates the error.
describe('Add one story to:\n\thttp://localhost:XXXX/api/stories', function () {
var testStory = new Story(
{
title: 'Mocha C title',
shortTitle: 'Mocha C shortTitle'
}
);
describe('Story object', function(){
describe('Save story object', function(){
it('should save without error', function(done){
testStory.save(done);
})
})
});
// ^ That test works
it('Should return 201 or 200', function (done) {
request(app)
.post('/api/stories/')
.send({
title: 'testing title',
shortTitle: 'testing short title'
})
.end(function(error, res) {
if(error) {
throw error;
}
done();
});
});
});
Here is my model containing schema and validation:
[story.js]
var mongoose = require('mongoose');
var StorySchema = new mongoose.Schema({
title: {
type: String,
required: true
},
shortTitle: String
});
module.exports = mongoose.model('Story', StorySchema);
I also have defined a controller:
[stories.js]
var Story = require('../models/story');
exports.postStory = function(req,res,next) {
var story = new Story();
story.title = req.body.title;
story.shortTitle = req.body.shortTitle;
story.save(function(err) {
if(err) {
res.send(err);
next();
} else {
res.status(201).json({
message: 'Story added successfully.', data: story
});
}
});
};
My express index.js:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var storyRoute = require('./routes/story');
var userRoute = require('./routes/user');
var app = express();
mongoose.connect('mongodb://localhost:27017/dbnamehere');
app.use(bodyParser.urlencoded({
extended: true
}));
var router = express.Router();
router.get('/', function(request, response) {
response.json({
message: 'Welcome to the dotStory API'
});
});
router.route('/stories')
.post(storyRoute.postStory);
app.use('/api', router);
module.exports = app;
Try to add json parser to your express application
// parse application/json
app.use(bodyParser.json());