-
Notifications
You must be signed in to change notification settings - Fork 290
/
test-db-setup.js
56 lines (52 loc) · 1.27 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
import mongoose from 'mongoose'
import cuid from 'cuid'
import config from './src/config'
import _ from 'lodash'
import { User } from './src/types/user/user.model'
import { Product } from './src/types/product/product.model'
import { Coupon } from './src/types/coupon/coupon.model'
const models = { Coupon, Product, User }
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(
config.dbUrl + 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()
})