如何在NodeJS中设置MongoDB进行集成测试?

Luk*_*cki 7 integration-testing embedded-database mongoose mongodb node.js

我正在为使用MongoDB编写的NodeJS中的应用程序编写集成测试.

在CI服务器上,我希望有一些嵌入式MongoDB,以实现更快的性能和更轻松的控制.目前我在其他服务器上安装了MongoDB,但测试速度很慢.在每次测试之前,我需要删除所有集合.我使用猫鼬作为ORM.

到目前为止,我只发现了嵌入式MongoDB for Java.

Dav*_*don 6

在撰写本文时,我建议使用mongodb-memory-server。该软件包将 mongod 二进制文件下载到您的主目录,并根据需要实例化一个新的内存支持的 MondoDB 实例。这应该很适合您的 CI 设置,因为您可以为每组测试启动一个新服务器,这意味着您可以并行运行它们。

有关如何将其与 mongoose 一起使用的详细信息,请参阅文档。


对于使用jest本机 mongodb 驱动程序的读者,您可能会发现此类很有用:

const { MongoClient } = require('mongodb');
const { MongoMemoryServer } = require('mongodb-memory-server');

// Extend the default timeout so MongoDB binaries can download
jest.setTimeout(60000);

// List your collection names here
const COLLECTIONS = [];

class DBManager {
  constructor() {
    this.db = null;
    this.server = new MongoMemoryServer();
    this.connection = null;
  }

  async start() {
    const url = await this.server.getUri();
    this.connection = await MongoClient.connect(url, { useNewUrlParser: true });
    this.db = this.connection.db(await this.server.getDbName());
  }

  stop() {
    this.connection.close();
    return this.server.stop();
  }

  cleanup() {
    return Promise.all(COLLECTIONS.map(c => this.db.collection(c).remove({})));
  }
}

module.exports = DBManager;
Run Code Online (Sandbox Code Playgroud)

然后在每个测试文件中您可以执行以下操作:

const dbman = new DBManager();

afterAll(() => dbman.stop());
beforeAll(() => dbman.start());
afterEach(() => dbman.cleanup());
Run Code Online (Sandbox Code Playgroud)


小智 0

我们的团队一直在消除 mongo 皮肤调用。根据您的测试包,您可以做同样的事情。这需要一些工作,但这是值得的。创建一个存根函数,然后声明您在测试中需要的内容。

   // Object based stubbing
    function createObjStub(obj) {
      return {
        getDb: function() {
         return {
            collection: function() {
              var coll = {};

              for (var name in obj) {
                var func = obj[name];

                if (typeof func === 'object') {
                  coll = func;
                } else {
                  coll[name] = func;
                }
              }

              return coll;
            }
          };
        }
      }
   }; 
    // Stubbed mongodb call
      var moduleSvc = new ModulesService(createObjStub({
        findById: function(query, options, cb) {
          return cb({
             'name': 'test'
           }, null);
           //return cb(null, null);
        }
      }),{getProperties: function(){return{get: function(){} }; } });
Run Code Online (Sandbox Code Playgroud)