我正在使用 MongoDB 数据库为我的 NodeJS 应用程序编写一些集成和系统测试。我使用的测试框架是Mocha和Supertest。是否可以将 MongoDB 设置为内存数据库,我只能用它来测试,然后在测试完成后擦除我的所有集合和文档?
您可以使用以下方法来完成此操作mongodb 内存服务器 https://www.npmjs.com/package/mongodb-memory-server。该软件包将 mongod 二进制文件下载到您的主目录,并根据需要实例化一个新的内存支持的 MondoDB 实例。对于每个测试文件,您可以启动一个新服务器,这意味着您可以并行运行它们。
供读者使用jest https://jestjs.io和原生 mongodb 驱动 https://www.npmjs.com/package/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;
然后在每个测试文件中您可以执行以下操作:
const dbman = new DBManager();
afterAll(() => dbman.stop());
beforeAll(() => dbman.start());
afterEach(() => dbman.cleanup());
我怀疑这种方法对于其他测试框架可能是类似的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)