我正在尝试为我的 express 应用程序的 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;