-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
135 lines (112 loc) · 2.72 KB
/
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
const tap = require('tap')
const Fastify = require('fastify')
const plugin = require('.')
const { test } = tap
test('Decorates fastify instance with db | without name', t => {
t.plan(4)
register(t, { url: 'db', collections: ['a'] }, function (err, fastify) {
t.error(err)
t.equal(typeof fastify.mongo, 'object')
fastify.mongo.stats((err, res) => {
t.error(err)
t.equal(res.db, 'db')
})
})
})
test('Decorates fastify instance with db | with name', t => {
t.plan(4)
register(t, {
name: 'db1',
url: 'db1',
collections: ['a']
}, function (err, fastify) {
t.error(err)
t.equal(typeof fastify.db1, 'object')
fastify['db1'].stats((err, res) => {
t.error(err)
t.equal(res.db, 'db1')
})
})
})
test('Paseses empty array if opts.collections missing', t => {
t.plan(4)
register(t, {
name: 'db1',
url: 'db1'
}, function (err, fastify) {
t.error(err)
t.equal(typeof fastify.db1, 'object')
fastify['db1'].stats((err, res) => {
t.error(err)
t.equal(res.collections, 0)
})
})
})
test('Throws if options.url not provided', t => {
t.plan(2)
register(t, {}, function (err, fastify) {
t.ok(err instanceof Error)
t.match(err.message, /url option is mandatory/)
})
})
test('Throws if options.name has registered', t => {
t.plan(2)
const fastify = Fastify()
t.teardown(() => fastify.close())
fastify
.decorate('alpha', {})
.register(plugin, {
name: 'alpha',
url: 'db'
})
.ready(err => {
t.ok(err instanceof Error)
t.match(err.message, /Decorator alpha has registered/)
})
})
test('Handles multiple connections', t => {
t.plan(7)
const fastify = Fastify()
t.teardown(() => fastify.close())
fastify
.register(plugin, {
name: 'alpha',
url: 'db1'
})
.register(plugin, {
name: 'beta',
url: 'db2'
})
.ready(err => {
t.error(err)
t.ok(fastify.alpha)
t.ok(fastify.beta)
fastify.alpha.stats((err, res) => {
t.error(err)
t.equal(res.db, 'db1')
})
fastify.beta.stats((err, res) => {
t.error(err)
t.equal(res.db, 'db2')
})
})
})
test('Handles mongojs error', t => {
t.plan(3)
register(t, {
url: 'mongodb://1.0.0.1:27017/db?connectTimeoutMS=100',
collections: ['a']
}, function (err, fastify) {
t.error(err)
fastify.mongo.runCommand({ ping: 1 }, function (err) {
t.ok(err instanceof Error)
t.match(err.message, /failed to connect to server/)
})
})
})
function register (t, options, callback) {
const fastify = Fastify()
t.teardown(() => fastify.close())
fastify.register(plugin, options)
.ready(err => callback(err, fastify))
}