SINON存根输出模块在中间件中的作用

本教程将介绍SINON存根输出模块在中间件中的作用的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

SINON存根输出模块在中间件中的作用 教程 第1张

问题描述

基于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)

推荐答案

基于answer。您可以为reqres对象和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);
  });
});

好了关于SINON存根输出模块在中间件中的作用的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。