node.js - 用于测试的内存 MongoDB?

我正在使用 MongoDB 数据库为我的 NodeJS 应用程序编写一些集成和系统测试。我使用的测试框架是 Mocha 和 Supertest。是否可以将 MongoDB 设置为内存数据库,我只能使用它进行测试,然后在测试完成后删除我所有的集合和文档?

最佳答案

您可以使用 mongodb-memory-server 完成此操作.该软件包将 mongod 二进制文件下载到您的主目录,并根据需要实例化一个新的内存支持 MondoDB 实例。对于每个测试文件,您都可以启动一个新服务器,这意味着您可以并行运行它们。


对于使用 jest 的读者和 native mongodb driver ,你可能会发现这个类很有用:

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;

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

const dbman = new DBManager();

afterAll(() => dbman.stop());
beforeAll(() => dbman.start());
afterEach(() => dbman.cleanup());

我怀疑这种方法可能与其他测试框架类似。

https://stackoverflow.com/questions/13607732/

相关文章:

mongodb - MongoDB 的 fsync 是做什么用的?

mongodb - 设置 MongoDB 数据库配额 (SIZE)

mongodb - 选择/配置数据库以获得高吞吐量、可靠、一致的写入吞吐量,牺牲延迟

node.js - 从 Mongoose 模型中找到的 native 驱动程序不返回光标

php - MongoDB/Doctrine : can't nest $or in $and

node.js - 我应该将图像存储在 MongoDB 中还是本地文件系统中(通过 Node.js)

python - 具有以列表中指定的前缀开头的属性的对象的 MongoEngine 查询列表

javascript - 在第二次保存操作中未调用子文档的 Mongoose 预保存中间件

ruby-on-rails - 获取字段最大值的对象[Mongoid]

java - MongoDB : how to index the keys of a Map