Skip to content

Commit

Permalink
Use memory mongo servrr while testing
Browse files Browse the repository at this point in the history
  • Loading branch information
hagopj13 committed Nov 8, 2019
1 parent e28cee0 commit 28e90a6
Show file tree
Hide file tree
Showing 5 changed files with 338 additions and 18 deletions.
1 change: 0 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
PORT=3000
MONGODB_URL=mongodb://127.0.0.1:27017/node-boilerplate
MONGODB_TEST_URL=mongodb://127.0.0.1:27017/node-boilerplate-test
JWT_SECRET=thisisasamplesecret
JWT_ACCESS_EXPIRATION_MINUTES=30
JWT_REFRESH_EXPIRATION_DAYS=30
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"husky": "^3.0.9",
"jest": "^24.9.0",
"lint-staged": "^9.4.2",
"mongodb-memory-server": "^6.0.1",
"node-mocks-http": "^1.8.0",
"nodemon": "^1.19.4",
"prettier": "^1.18.2",
Expand Down
2 changes: 1 addition & 1 deletion src/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = {
env: process.env.NODE_ENV,
port: process.env.PORT,
mongoose: {
url: process.env.NODE_ENV === 'test' ? process.env.MONGODB_TEST_URL : process.env.MONGODB_URL,
url: process.env.MONGODB_URL,
options: { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true },
},
jwt: {
Expand Down
12 changes: 7 additions & 5 deletions tests/utils/setupDatabase.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
const mongoose = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server');
const config = require('../../src/config/config');

const clearDatabase = async () => {
await Promise.all(Object.values(mongoose.connection.collections).map(async collection => collection.deleteMany()));
};
let mongod;

const setupDatabase = () => {
beforeAll(async () => {
await mongoose.connect(config.mongoose.url, config.mongoose.options);
mongod = new MongoMemoryServer();
const uri = await mongod.getUri();
await mongoose.connect(uri, config.mongoose.options);
});

beforeEach(async () => {
await clearDatabase();
await Promise.all(Object.values(mongoose.connection.collections).map(async collection => collection.deleteMany()));
});

afterAll(async () => {
await mongoose.disconnect();
await mongod.stop();
});
};

Expand Down
Loading

0 comments on commit 28e90a6

Please sign in to comment.