"没有发现听众"验证错误Mongoose和Mocha

时间:2014-12-08 07:17:25

标签: node.js express mongoose mocha supertest

我正在尝试为我的快递应用程序的POST功能设置单元测试。

我有以下简单的Mongoose模式,其中包含两个字段,其中一个是必需的。

当我关闭验证/必填字段进行mocha测试时,测试很好,但是当required设置为true时,测试会出现以下错误:

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

有什么想法吗?正如您所看到的,我确实满足了架构要求,并且包含了标题字段。

以下是我的测试:有趣的是,第一个测试似乎工作正常,只有当我尝试发布时才会生成错误。



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




这是我的模型包含架构和验证:

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




1 个答案:

答案 0 :(得分:1)

尝试将json parser添加到您的快速申请

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