【发布时间】:2022-01-18 11:05:56
【问题描述】:
基于this question,我还需要对同样使用db-connection.js 文件的中间件进行测试。中间件文件如下所示:
const dbConnection = require('./db-connection.js')
module.exports = function (...args) {
return async function (req, res, next) {
// somethin' somethin' ...
const dbClient = dbConnection.db
const docs = await dbClient.collection('test').find()
if (!docs) {
return next(Boom.forbidden())
}
}
}
,数据库连接文件不变,即:
const MongoClient = require('mongodb').MongoClient
const dbName = 'test'
const url = process.env.MONGO_URL
const client = new MongoClient(url, { useNewUrlParser: true,
useUnifiedTopology: true,
bufferMaxEntries: 0 // dont buffer querys when not connected
})
const init = () => {
return client.connect().then(() => {
logger.info(`mongdb db:${dbName} connected`)
const db = client.db(dbName)
})
}
/**
* @type {Connection}
*/
module.exports = {
init,
client,
get db () {
return client.db(dbName)
}
}
中间件的工作原理是通过传递字符串列表(字符串是角色),我必须查询数据库并检查是否有每个角色的记录。如果记录存在,我将返回next(),如果记录不存在,我将返回next(Boom.forbidden())(下一个函数,来自 Boom 模块的 403 状态码)。
鉴于上面的细节,如果记录存在与否,如何进行测试以测试中间件的返回值?这意味着我必须准确地断言next() 和next(Boom.forbidden)。
【问题讨论】:
标签: javascript node.js unit-testing sinon node-mongodb-native