在内存中使用MongoDB进行测试? [英] In-memory MongoDB for test?
问题描述
我正在使用MongoDB数据库为NodeJS应用程序编写一些集成和系统测试.我使用的测试框架是Mocha和Supertest.是否可以将MongoDB设置为内存数据库,我只能使用它进行测试,然后在测试完成后擦除所有的收藏和文档?
I am writing some integration and system tests for my NodeJS application using a MongoDB database. The test framework I use is Mocha and Supertest. Is it possible to setup MongoDB as an in-memory database which I can use to only test which then wipes away all my collections and documents when the test is done?
推荐答案
您可以使用 mongodb-memory-server .程序包将mongod二进制文件下载到您的主目录,并根据需要实例化一个新的支持内存的MondoDB实例.对于每个测试文件,您都可以启动一个新服务器,这意味着您可以并行运行它们.
You can accomplish this using mongodb-memory-server. The package downloads a mongod binary to your home directory and instantiates a new memory-backed MondoDB instance as needed. For each test file you can spin up a new server which means you can run them all parallel.
对于使用笑话和
For readers using jest and the native mongodb driver, you may find this class useful:
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.getConnectionString();
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;
然后在每个测试文件中,您可以执行以下操作:
Then in each test file you can do the following:
const dbman = new DBManager();
afterAll(() => dbman.stop());
beforeAll(() => dbman.start());
afterEach(() => dbman.cleanup());
我怀疑这种方法可能与其他测试框架相似.
I suspect this approach may be similar for other testing frameworks.
这篇关于在内存中使用MongoDB进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!