基于這個問題,我還需要對也使用該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()and 。next(Boom.forbidden)
uj5u.com熱心網友回復:
根據答案。req您可以為、res物件和next函式創建存根。
例如(不運行,但它應該作業。)
const sinon = require('sinon');
describe('a', () => {
afterEach(() => {
sinon.restore();
});
it('should find some docs', async () => {
process.env.MONGO_URL = 'mongodb://localhost:27017';
const a = require('./a');
const dbConnection = require('./db-connection.js');
const dbStub = {
collection: sinon.stub().returnsThis(),
find: sinon.stub(),
};
sinon.stub(dbConnection, 'db').get(() => dbStub);
const req = {};
const res = {};
const next = sinon.stub();
const actual = await a()(req, res, next);
sinon.assert.match(actual, true);
sinon.assert.calledWithExactly(dbStub.collection, 'test');
sinon.assert.calledOnce(dbStub.find);
sinon.assert.calledOnce(next);
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/414955.html
標籤:
上一篇:如何使用命令列引數進行單元測驗
