This repository has been archived by the owner on Mar 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.test.js
100 lines (85 loc) · 2.23 KB
/
db.test.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/* eslint-disable */
jest.mock('./logger')
process.env.DATABASE_USER = 'user'
process.env.DATABASE_PASSWORD = 'password'
process.env.DATABASE_ADDRESS = 'address'
process.env.DATABASE_NAME = 'name'
const uri = `mongodb://${process.env.DATABASE_USER}:${process.env.DATABASE_PASSWORD}@${process.env.DATABASE_ADDRESS}/${process.env.DATABASE_NAME}`
beforeEach(() => {
jest.resetModules()
})
test('creates connection with right uri', done => {
jest.setMock('mongoose', {
createConnection: function (u, os) {
expect(u).toBe(uri)
done()
return {
on: jest.fn(),
once: jest.fn(),
close: jest.fn(),
}
},
})
require('./db')(uri, process.env.DATABASE_NAME)
})
test('resolves on connection open', () => {
jest.setMock('mongoose', {
createConnection: function (u, os) {
return {
id: 'connection',
on: jest.fn(),
once: function (event, cb) {
if (event === 'open')
cb()
},
close: jest.fn(),
}
},
})
expect.assertions(1)
require('./db')(uri, process.env.DATABASE_NAME)
.then(conn => {
expect(conn.id).toBe('connection')
})
})
test('retries on connection error', () => {
const createConnection = function (u, os) {
return {
on: function (event, cb) {
expect(event).toBe('error')
cb('no database connection')
},
once: jest.fn(),
close: jest.fn(),
}
}
jest.setMock('mongoose', { createConnection })
require('./db')(uri, process.env.DATABASE_NAME)
})
test('closes connection on SIGINT', done => {
const mockClose = jest.fn()
const createConnection = function (u, os) {
return {
on: jest.fn(),
once: jest.fn(),
close: mockClose,
}
}
jest
.setMock('mongoose', { createConnection })
const exit = jest.spyOn(process, 'exit').mockImplementation(c => c)
jest
.spyOn(process, 'on')
.mockImplementation((signal, cb) => {
expect(signal).toBe('SIGINT')
mockClose.mockImplementation((cb2) => {
jest.spyOn(process, 'exit').mockImplementation((code) => {
expect(code).toBe(0)
done()
})
cb2()
})
cb()
})
require('./db')(uri, process.env.DATABASE_NAME)
})