想象一下我這里有一個檔案:
// a.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())
}
}
}
,db-connection.js看起來像這樣:
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)
}
}
我有一個測驗來存根find()方法以至少回傳真(為了測驗a.js' 的回傳值是否為真。我該怎么做?
uj5u.com熱心網友回復:
單元測驗策略是對 DB 連接進行 stub,我們不需要連接真正的 mongo DB 服務器。這樣我們就可以在與外部環境隔離的環境中運行測驗用例。
您可以使用stub.get(getterFn)為 getter替換新的dbConnection.dbgetter。
由于 MongoDB 客戶端初始化發生在您需要db-connection模塊時。您應該在要求和模塊MongoClient之前從環境變數中提供正確的 URL 。否則,MongoDB nodejs 驅動會拋出一個無效的 url 錯誤。adb-connection
例如
a.js:
const dbConnection = require('./db-connection.js');
module.exports = function () {
const dbClient = dbConnection.db;
const docs = dbClient.collection('test').find();
if (!docs) {
return true;
}
};
db-connection.js:
const MongoClient = require('mongodb').MongoClient;
const dbName = 'test';
const url = process.env.MONGO_URL;
const client = new MongoClient(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const init = () => {
return client.connect().then(() => {
console.info(`mongdb db:${dbName} connected`);
const db = client.db(dbName);
});
};
module.exports = {
init,
client,
get db() {
return client.db(dbName);
},
};
a.test.js:
const sinon = require('sinon');
describe('a', () => {
afterEach(() => {
sinon.restore();
});
it('should find some docs', () => {
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 actual = a();
sinon.assert.match(actual, true);
sinon.assert.calledWithExactly(dbStub.collection, 'test');
sinon.assert.calledOnce(dbStub.find);
});
});
測驗結果:
a
? should find some docs (776ms)
1 passing (779ms)
------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------|---------|----------|---------|---------|-------------------
All files | 75 | 50 | 25 | 75 |
a.js | 100 | 50 | 100 | 100 | 7
db-connection.js | 60 | 100 | 0 | 60 | 11-13,21
------------------|---------|----------|---------|---------|-------------------
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/414958.html
標籤:
