-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-db-setup.js
More file actions
57 lines (51 loc) · 1.26 KB
/
test-db-setup.js
File metadata and controls
57 lines (51 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import mongoose from 'mongoose';
import cuid from 'cuid';
import _ from 'lodash';
import { Card } from './src/resources/card/card.model';
import { Deck } from './src/resources/deck/deck.model';
var models = { Card, Deck };
const url =
process.env.MONGODB_URI ||
process.env.DB_URL ||
'mongodb://localhost:27017/jest';
global.newId = () => {
return mongoose.Types.ObjectId();
};
const remove = collection =>
new Promise((resolve, reject) => {
collection.remove(err => {
if (err) return reject(err);
resolve();
});
});
beforeEach(async done => {
const db = cuid();
function clearDB() {
return Promise.all(_.map(mongoose.connection.collections, c => remove(c)));
}
if (mongoose.connection.readyState === 0) {
try {
await mongoose.connect(url + db, {
useNewUrlParser: true,
autoIndex: true
});
await clearDB();
await Promise.all(Object.keys(models).map(name => models[name].init()));
} catch (e) {
console.log('connection error');
console.error(e);
throw e;
}
} else {
await clearDB();
}
done();
});
afterEach(async done => {
await mongoose.connection.db.dropDatabase();
await mongoose.disconnect();
return done();
});
afterAll(done => {
return done();
});