/
index.js
122 lines (84 loc) · 3.03 KB
/
index.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
'use strict';
const Code = require('@hapi/code');
const Hapi = require('@hapi/hapi');
const Lab = require('@hapi/lab');
const Path = require('path');
const Proxyquire = require('proxyquire');
const lab = exports.lab = Lab.script();
const config = {
mongodb: {
connection: {
uri: process.env.MONGODB_URI || 'mongodb://localhost:27017/',
db: 'hapi-mongo-models-test'
},
options: {}
},
models: [
Path.resolve(__dirname, 'fixtures/dummy-model'),
Path.resolve(__dirname, 'fixtures/noindex-model')
]
};
const stub = {
MongoModels: {}
};
const HapiMongoModels = Proxyquire('..', {
'mongo-models': stub.MongoModels
});
lab.experiment('Plugin', () => {
lab.test('it throws an error when the db connection fails', async () => {
const realConnect = stub.MongoModels.connect;
stub.MongoModels.connect = function (connection, options) {
throw Error('connect failed');
};
const server = Hapi.Server();
const plugin = {
plugin: HapiMongoModels,
options: config
};
const throws = async function () {
await server.register(plugin);
};
await Code.expect(throws()).to.reject();
stub.MongoModels.connect = realConnect;
});
lab.test('it successfuly connects and exposes the plugin (default autoIndex value)', async () => {
const server = Hapi.Server();
const plugin = {
plugin: HapiMongoModels,
options: config
};
await server.register(plugin);
await server.start();
Code.expect(server.plugins['hapi-mongo-models']).to.be.an.object();
server.plugins['hapi-mongo-models']['mongo-models'].disconnect();
await server.stop();
});
lab.test('it connects to the db and creates indexes during pre-start (autoIndex set manually)', async () => {
const configClone = JSON.parse(JSON.stringify(config));
configClone.autoIndex = true;
const server = Hapi.Server();
const plugin = {
plugin: HapiMongoModels,
options: configClone
};
await server.register(plugin);
await server.start();
Code.expect(server.plugins['hapi-mongo-models']).to.be.an.object();
server.plugins['hapi-mongo-models']['mongo-models'].disconnect();
await server.stop();
});
lab.test('it connects to the db and skips creating indexes during pre-start (autoIndex set manually)', async () => {
const configClone = JSON.parse(JSON.stringify(config));
configClone.autoIndex = false;
const server = Hapi.Server();
const plugin = {
plugin: HapiMongoModels,
options: configClone
};
await server.register(plugin);
await server.start();
Code.expect(server.plugins['hapi-mongo-models']).to.be.an.object();
server.plugins['hapi-mongo-models']['mongo-models'].disconnect();
await server.stop();
});
});