gpt4 book ai didi

node.js - 如何为 NodeJS 中的集成测试设置 MongoDB?

转载 作者:IT老高 更新时间:2023-10-28 12:30:57 25 4
gpt4 key购买 nike

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

在 CI 服务器上,我希望拥有某种嵌入式 MongoDB,以实现更快的性能和更轻松的控制。目前我在其他服务器上有 MongoDB,但测试很慢。在每次测试之前,我需要删除所有集合。我使用 Mongoose 作为 ORM。

到目前为止,我只找到了嵌入式 MongoDB for Java。

最佳答案

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

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


对于使用 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());

关于node.js - 如何为 NodeJS 中的集成测试设置 MongoDB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17342144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com