An abstraction layer for the mongodb package to facilitate handling database fixtures for testing purposes, in a MongoDB database. This package is ment to be used in conjunction with the dbfixtures package, but can also be used by itself.
npm install dbfixtures-mongodb-driver
This package exposes the create({ connectURI: string, connectOptions?: MongoClientOptions, dbName: string, dbOptions?: MongoClientCommonOption }): Promise<IDriver>
function that returns a Promise that resolves with an instance of the driver.
Note1: For detailed information about the connectURI
and connectOptions
arguments, please consult the MongoDB NodeJS driver's connect documentation.
Note2: For detailed information about the MongoClientCommonOption
argument, please consult the MongoDB NodeJS driver's DB documentation.
An instance of the driver exposes the following interface
// truncates the collections (i.e., "tables") with the supplied names
truncate: (tableNames: string[]) => Promise<void>
// inserts the supplied documents into the specified collection (i.e., "table")
insertFixtures: (tableName: string, fixtures: [{}]) => Promise<void>
// terminates the connection to the database
close: () => Promise<void>
This example uses Mocha as the potential test runner.
const dbfixtures = require('dbfixtures');
const fixturesMongoDriver = require('dbfixtures-mongo-driver');
const mongodbDriverInfo = {
connectURI: 'mongodb://localhost:27017/',
connectOptions: { useNewUrlParser: true },
dbName: 'test',
};
const fixtures = {
'roles': [
{ id: 1, name: 'role 1' },
{ id: 2, name: 'role 2' },
],
'users': [
{ id: 1, email: 'myemail@test.net', role_id: 2 },
{ id: 2, email: 'test@gmail.com', role_id: 1 },
{ id: 3, email: 'another@email.org', role_id: 1 },
],
};
describe('fixtures example', function () {
before(async function () {
const mongodbDriver = await fixturesMongoDriver.create(mongodbDriverInfo);
dbfixtures.setDrivers(mongodbDriver);
});
after(async function () {
await dbfixtures.closeDrivers();
});
beforeEach(async function () {
await dbfixtures.insertFixtures(fixtures);
});
it('should have the database seeded with the fixtures', function () {
// ...
});
});
-
cd
into the package's directory -
run
npm install
-
run
npm run build
-
for unit tests run
npm test -- test\unit\
-
for integration tests run
npm test -- test\integration\
NOTE: requires an active MongoDB server available atlocalhost:27017
-
for end-to-end tests run
npm test -- test\e2e\
NOTE: requires an active MongoDB server available atlocalhost:27017
If you are using Docker
, you can run the CLI command docker run --name testmongo -p 127.0.0.1:27017:27017/tcp mongo:4
to raise a container with the MongoDB v4.* image and make it available through localhost:27017
.