学习如何使用Mocha,Chai,Chai-HTTP插件和MongoDB与Mongoose一起使用Express进行测试。我有一个测试来专门检测MongoDB是否会发送回一个错误,因为试图使用错误值(太短)查找文档。_id
我注意到我的部分代码正在我的其他Express路由周围重复,并希望将其重用于其他路由,因此我从另一个模块中导出了它,但现在我得到了这个:
Uncaught Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
不知道为什么我收到此错误。如果我有相同的代码,作为导出的函数,在路由代码内部它工作正常,但导出它只是抱怨。
代码如下:
test/route/example.test.js截图
it('Bad request with a too short ID string (12 characters minimum)', () => {
// /api/v1/example is the endpoint
// /blah is the param
chai.request(app).get('/api/v1/example/blah').end((err, res) => {
// Insert all the nice assert stuff. :)
});
});
路由/示例.js截图
// Packages
const router = require('express').Router();
// Models (Mongoose Schemas)
const Example = require('../models/example.model');
// Helpers
const { foundMongoError } = require('../helpers/routes');
// -----Snipped-----
router.route('/:exampleId').get((req, res) => {
// Retrieve the exampleId parameter.
const exampleId = req.params.exampleId;
Example.findById(exampleId, (mongoError, mongoResponse) => {
foundMongoError(mongoError, res); // Having an issue
// If I have the same code that makes up foundMongoError inside here, no issues,
// but it will no longer be DRY.
// Check if any responses from MongoDB
if(mongoResponse) {
res.status(200).json(mongoResponse);
} else {
return res.status(404).json({
errorCode: 404,
errorCodeMessage: 'Not Found',
errorMessage: `Unable to find example with id: ${exampleId}.`
});
}
});
});
助手/路线.js
const foundMongoError = (mongoError, res) => {
if(mongoError) {
return res.status(400).json({
errorCode: 400,
errorCodeMessage: 'Bad Request',
errorMessage: mongoError.message
});
}
};
module.exports = {
foundMongoError
};
达令说
相关分类