forked from FrontendMasters/api-design-node-v3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test-db-setup.js
61 lines (55 loc) · 1.34 KB
/
test-db-setup.js
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
58
59
60
61
import mongoose from 'mongoose'
import cuid from 'cuid'
import _ from 'lodash'
import { Item } from './src/resources/item/item.model'
import { List } from './src/resources/list/list.model'
import { User } from './src/resources/user/user.model'
const models = { User, List, Item }
const url =
process.env.MONGODB_URI ||
process.env.DB_URL ||
'mongodb://localhost:27017/tipe-devapi-testing'
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()
})