使用 mocha 框架运行测试时保持 MongoDB 连接打开 [英] Keep MongoDB connection open while running tests using mocha framework

查看:46
本文介绍了使用 mocha 框架运行测试时保持 MongoDB 连接打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用类似于 如何跨 NodeJs 应用程序和模块正确重用与 Mongodb 的连接 以保持我的 mongoDB 连接打开.
这需要将所有代码放入 MongoDB.connectDB(async (err) => {...} 块.
使用 Mocha 编写测试时我将如何使用它.
我是否必须为每个测试使用单独的连接?像这样?

I'm using something akin to How to properly reuse connection to Mongodb across NodeJs application and modules to keep my mongoDB Connection open.
This requires all the code to go into a MongoDB.connectDB(async (err) => {...} Block.
How would I use this when writing Tests with Mocha.
Do I have to use a separate Connection for every test? Like this?

const MongoDB = require('../src/mongoUtil') // providing access to the mongo database
var events = require('../src/events') // containing all my database Functions

describe('events.js', function () {
  describe('addEvent()', function () {
    it('should return the event, when added succesfully', async function () {
      await MongoDB.connectDB(async (err) => {
        if (err) throw err

        const database = MongoDB.getDB()
        const eventsCollection = database.db().collection('events')

        const event = {
          name: 'test Event',
          members: []
        }

        const result = await events.addEvent(eventsCollection, event)

        MongoDB.disconnectDB()

        if (result.name !== event.name) {
          return new Error('TODO')
        }
      })
    })
  })
})

为了让这个例子正常工作,如果我正确理解了 mocha 网站,我可能还必须手动将测试设置为完成?
我可以只有一个连接吗?

For this example to work properly I probably also have to manually set the test to done, if I understood the mocha website correctly?
Can I have just one connection?

mongoUtil.js

mongoUtil.js

const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://localhost:27017/testing'

let _db

const connectDB = async (callback) => {
  try {
    MongoClient.connect(uri, { useNewUrlParser: true }, (err, db) => {
      _db = db
      return callback(err)
    })
  } catch (e) {
    throw e
  }
}

const getDB = () => _db

const disconnectDB = () => _db.close()

module.exports = { connectDB, getDB, disconnectDB }

事件.js

const addEvent = async (collection, event) => {
  try {
    const exists = await collection.findOne({ 'name': event.name })
    if (exists) {
      return false
    } else {
      const results = await collection.insertOne(event)
      return results.ops[0]
    }
  } catch (e) {
    throw e
  }
}
module.exports = { addEvent }

推荐答案

您不需要将所有内容都放在 MongoDB.connectDB({...}) 中.这称为回调地狱,应尽可能避免.mongoUtil 是不方便的包装器,它不会使 MongoDB API 更简单或更易于使用.

You don't need to put everything inside MongoDB.connectDB({...}). This is called callback hell which should be avoided when possible. mongoUtil is inconvenient wrapper that doesn't make MongoDB API simpler or easier to use.

await MongoDB.connectDB(async (err) => { ... 是一个错误.将 async 函数作为回调是不够的,会导致控制流程不当.

await MongoDB.connectDB(async (err) => { ... is a mistake. Putting async function as a callback is not enough and will result in improper control flow.

MongoClient.connect 使用错误优先回调,因此它可以与 done 一起使用以将错误传递给测试套件:

MongoClient.connect uses error-first callbacks, so it can be used with done to pass errors to test suite:

let db;

beforeEach(done => {
  MongoClient.connect(uri, { useNewUrlParser: true }, (err, _db) => {
    db = _db;
    done(err);
  });
});

connectDB 错误地承诺 MongoClient.connect.当使用 promise 和 async..await 时,不需要一次性回调.可能是:

connectDB incorrectly promisifies MongoClient.connect. There's no need for one-time callbacks when promises and async..await are in use. It could be:

const connectDB = () => {
  return new Promise((resolve, reject) => {
    MongoClient.connect(uri, { useNewUrlParser: true }, (err, db) => {
      if (err) reject(err);
      else resolve(db);
    });
  });
};

但事实是,当省略回调参数时,mongodb 本机支持承诺.mongoUtil 只需要一个辅助函数,connectDB:

But the fact is that mongodb supports promises natively when callback argument is omitted. mongoUtil needs only one helper function, connectDB:

const connectDB = () => MongoClient.connect(uri, { useNewUrlParser: true });

可以无缝地与 Mocha 一起使用,因为它支持承诺:

Which can be used with Mocha seamlessly since it supports promises:

let db;

beforeEach(async () => {
  db = await connectDB();
});

afterEach(() => db.close());

close 是异步的,也返回一个 promise.

close is asynchronous and returns a promise, too.

这篇关于使用 mocha 框架运行测试时保持 MongoDB 连接打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆