“没有听众检测到”validation错误mongoose和摩卡

我正在尝试为我的快速应用程序的POST函数设置unit testing。

我有以下两个领域简单的mongoose纲要,其中一个是必需的。

当我在validation/必填字段closures的情况下进行摩卡testing时,testing是正确的,但是当所需设置为true时,testing失败,出现以下错误:

Uncaught: No listeners detected, throwing. Consider adding an error listener to your connection. ValidationError: Path 'title' is required 

有任何想法吗? 正如你所看到的,我肯定已经满足了模式要求,并且包含了标题字段。

这里是我的testing下面:有趣的是,第一个testing似乎工作正常,只有当我试图发布,它会产生错误。

 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(); }); }); }); 

这是我的模型包含模式和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); 

我也定义了一个控制器:

 [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 }); } }); }; 

我的快递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; 

尝试将jsonparsing器添加到您的快速应用程序

 // parse application/json app.use(bodyParser.json());