-
Notifications
You must be signed in to change notification settings - Fork 74
/
index.test.js
563 lines (472 loc) · 16.9 KB
/
index.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/* global jest, describe, test, expect, afterEach, beforeAll, beforeEach */
const { resolve } = require('path')
const { createHash } = require('crypto')
const webpack = require('webpack')
const { readFileSync } = require('fs')
const rimraf = require('rimraf')
const Src = require('../src')
const Dist = require('../dist')
const envEmpty = resolve(__dirname, './envs/.empty')
const envEmptyExample = resolve(__dirname, './envs/.empty.example')
const envSimple = resolve(__dirname, './envs/.simple')
const envSimpleExample = resolve(__dirname, './envs/.simple.example')
const envOneEmpty = resolve(__dirname, './envs/.oneempty')
const envOneEmptyExample = resolve(__dirname, './envs/.oneempty.example')
const envMissingOne = resolve(__dirname, './envs/.missingone')
const envMissingOneExample = resolve(__dirname, './envs/.missingone.example')
const envSystemvars = resolve(__dirname, './envs/.systemvars')
const envSystemvarsExample = resolve(__dirname, './envs/.systemvars.example')
const envExpanded = resolve(__dirname, './envs/.expanded')
const envDefaults = resolve(__dirname, './envs/.defaults')
const emptyResult = {}
const defaultEnvResult = { TEST: 'hi' }
const simpleResult = { TEST: 'testing' }
const defaultsResult = { TEST: 'hi', TEST2: 'hidefault' }
const defaultsResult2 = { TEST: 'hi', TEST2: 'youcanseethis' }
const oneEmptyResult = { TEST: '', TEST2: 'Hello' }
const missingOneResult = { TEST2: 'Hello' }
const altDefaultEnvResult = { TEST_ALT: 'hi' }
const altSimpleResult = { TEST_ALT: 'testing' }
const altDefaultsResult = { TEST_ALT: 'hi', TEST2_ALT: 'hidefault' }
const altDefaultsResult2 = { TEST_ALT: 'hi', TEST2_ALT: 'youcanseethis' }
const altOneEmptyResult = { TEST_ALT: '', TEST2_ALT: 'Hello' }
const hash = (str) => createHash('md5').update(str).digest('hex').slice(0, 8)
const getConfig = (target, plugin) => ({
mode: 'development',
devtool: false,
target,
entry: resolve(__dirname, './fixtures/index'),
output: {
path: resolve(__dirname, `./output/${hash(expect.getState().currentTestName)}`),
chunkFormat: 'commonjs'
},
plugins: [plugin]
})
const compile = (config, callback) => {
webpack(config, (err, stats) => {
expect(err).toBeNull()
expect(stats.compilation.errors).toHaveLength(0)
const result = readFileSync(
resolve(__dirname, config.output.path, 'main.js'),
{ encoding: 'utf-8' }
)
callback(result)
})
}
const expectResultsToContainReplacements = (plugin, env, done) => {
const config = getConfig('web', plugin)
compile(config, (result) => {
Object.entries(env).forEach(([key, value]) => {
expect(result).toMatch(`const ${key} = "${value}"`)
})
done?.()
})
}
const versions = [
['Source', Src.default],
['Dist', Dist.default]
]
beforeAll(() => {
global.console.warn = jest.fn()
})
beforeEach((done) => {
jest.resetAllMocks()
const outputDir = resolve(__dirname, `output/${hash(expect.getState().currentTestName)}`)
rimraf(outputDir, done)
})
describe.each(versions)('%s', (_, DotenvPlugin) => {
test('Should be an function.', () => {
expect(typeof DotenvPlugin).toEqual('function')
})
test('Should return a instance of Dotenv.', () => {
expect((new DotenvPlugin()).constructor.name).toEqual('Dotenv')
})
describe('Defaults', () => {
test('Should include environment variables that exist in .env file.', (done) => {
expectResultsToContainReplacements(new DotenvPlugin(), defaultEnvResult, done)
})
test('Should not expand variables by default', (done) => {
const expected = {
NODE_ENV: 'test',
BASIC: 'basic',
BASIC_EXPAND: '$BASIC',
MACHINE: 'machine_env',
MACHINE_EXPAND: '$MACHINE',
UNDEFINED_EXPAND: '$UNDEFINED_ENV_KEY',
// eslint-disable-next-line
ESCAPED_EXPAND: '\\\\$ESCAPED',
MONGOLAB_DATABASE: 'heroku_db',
MONGOLAB_USER: 'username',
MONGOLAB_PASSWORD: 'password',
MONGOLAB_DOMAIN: 'abcd1234.mongolab.com',
MONGOLAB_PORT: '12345',
// eslint-disable-next-line
MONGOLAB_URI: 'mongodb:https://${MONGOLAB_USER}:${MONGOLAB_PASSWORD}@${MONGOLAB_DOMAIN}:${MONGOLAB_PORT}/${MONGOLAB_DATABASE}',
// eslint-disable-next-line
MONGOLAB_USER_RECURSIVELY: '${MONGOLAB_USER}:${MONGOLAB_PASSWORD}',
// eslint-disable-next-line
MONGOLAB_URI_RECURSIVELY: 'mongodb:https://${MONGOLAB_USER_RECURSIVELY}@${MONGOLAB_DOMAIN}:${MONGOLAB_PORT}/${MONGOLAB_DATABASE}',
WITHOUT_CURLY_BRACES_URI: 'mongodb:https://$MONGOLAB_USER:$MONGOLAB_PASSWORD@$MONGOLAB_DOMAIN:$MONGOLAB_PORT/$MONGOLAB_DATABASE',
WITHOUT_CURLY_BRACES_USER_RECURSIVELY: '$MONGOLAB_USER:$MONGOLAB_PASSWORD',
WITHOUT_CURLY_BRACES_URI_RECURSIVELY: 'mongodb:https://$MONGOLAB_USER_RECURSIVELY@$MONGOLAB_DOMAIN:$MONGOLAB_PORT/$MONGOLAB_DATABASE'
}
expectResultsToContainReplacements(
new DotenvPlugin({ path: envExpanded }),
expected,
done
)
})
test('Should expand variables when configured', (done) => {
const expected = {
NODE_ENV: 'test',
BASIC: 'basic',
BASIC_EXPAND: 'basic',
MACHINE: 'machine_env',
MACHINE_EXPAND: 'machine_env',
UNDEFINED_EXPAND: '',
// eslint-disable-next-line
ESCAPED_EXPAND: '\$ESCAPED',
MONGOLAB_DATABASE: 'heroku_db',
MONGOLAB_USER: 'username',
MONGOLAB_PASSWORD: 'password',
MONGOLAB_DOMAIN: 'abcd1234.mongolab.com',
MONGOLAB_PORT: '12345',
MONGOLAB_URI: 'mongodb:https://username:[email protected]:12345/heroku_db',
MONGOLAB_USER_RECURSIVELY: 'username:password',
MONGOLAB_URI_RECURSIVELY: 'mongodb:https://username:[email protected]:12345/heroku_db',
WITHOUT_CURLY_BRACES_URI: 'mongodb:https://username:[email protected]:12345/heroku_db',
WITHOUT_CURLY_BRACES_USER_RECURSIVELY: 'username:password',
WITHOUT_CURLY_BRACES_URI_RECURSIVELY: 'mongodb:https://username:[email protected]:12345/heroku_db'
}
expectResultsToContainReplacements(
new DotenvPlugin({ path: envExpanded, expand: true }),
expected,
done
)
})
})
describe('Simple configuration', () => {
test('Should load enviornment variables when they exist in the .env file.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envSimple }),
simpleResult,
done
)
})
test('Should be an empty object when no environment variables exist in .env file.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: false }),
emptyResult,
done
)
})
test('Should recognize safe-mode', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ safe: true }),
defaultEnvResult,
done
)
})
test('Should fail when not passing safe-mode', (done) => {
const config = getConfig('web', new DotenvPlugin({ path: envMissingOne, safe: true }))
webpack(config, (err) => {
expect(err.message).toBe('Missing environment variable: TEST')
done()
})
})
})
describe('Safe configuration', () => {
test('Should load successfully if variables defined', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envEmpty, safe: envEmptyExample }),
emptyResult,
() => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envSimple, safe: envSimpleExample }),
simpleResult,
done
)
}
)
})
test('Should fail if env does not match sample.', (done) => {
const config = getConfig(
'web',
new DotenvPlugin({ path: envEmpty, safe: envSimpleExample })
)
webpack(config, (err) => {
expect(err.message).toBe('Missing environment variable: TEST')
done()
})
})
})
describe('Defaults configuration', () => {
test('should support default configurations', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ defaults: true }),
defaultsResult,
done
)
})
test('should support string configurations', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ defaults: envDefaults }),
defaultsResult2,
done
)
})
test('Should display warning when default cannot be loaded', (done) => {
const envDefaultName = '.does.not.exist'
expectResultsToContainReplacements(
new DotenvPlugin({ defaults: envDefaultName }),
defaultEnvResult,
done
)
expect(global.console.warn).toHaveBeenCalledWith(`Failed to load ${envDefaultName}.`)
})
})
describe('System variables', () => {
const originalPath = process.env.PATH
beforeEach(() => {
process.env.PATH = '/usr/local/bin:/usr/local/sbin:'
})
afterEach(() => {
process.env.PATH = originalPath
})
test('Should allow system env variables', (done) => {
const config = getConfig(
'web',
new DotenvPlugin({ path: envSimple, systemvars: true })
)
compile(config, (result) => {
expect(result).toMatch('const TEST = "testing"')
expect(result).toMatch('const PATH = "/usr/local/bin:/usr/local/sbin:')
done()
})
})
test('should pass if the systemvar satisfies the requirement', (done) => {
const config = getConfig(
'web',
new DotenvPlugin({ safe: envSystemvarsExample, systemvars: true })
)
compile(config, (result) => {
expect(result).toMatch('const TEST = "hi"')
expect(result).toMatch(/const PATH = ".*[\\/].*"/)
done()
})
})
test('should not allow local variables to override systemvars', (done) => {
const config = getConfig(
'web',
new DotenvPlugin({ path: envSystemvars, systemvars: true })
)
compile(config, (result) => {
expect(result).toMatch('const TEST = "MISSING_ENV_VAR".TEST')
expect(result).not.toMatch('const PATH = ""')
done()
})
})
test('Should give the highest priority for the system variables', (done) => {
process.env.TEST = 'production'
const config = getConfig(
'web',
new DotenvPlugin({ safe: true, systemvars: true, defaults: true })
)
compile(config, (result) => {
expect(result).toMatch('const TEST = "production"')
expect(result).toMatch('const TEST2 = "hidefault"')
done()
})
delete process.env.TEST
})
})
describe('Empty variables', () => {
test('Should load fine (not-safe)', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envOneEmpty }),
oneEmptyResult,
done
)
})
test('Should fail on safe mode', (done) => {
const config = getConfig(
'web',
new DotenvPlugin({ path: envOneEmpty, safe: envOneEmptyExample })
)
webpack(config, (err) => {
expect(err.message).toBe('Missing environment variable: TEST')
done()
})
})
test('Should succeed in safe mode if allowEmptyValues is true', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envOneEmpty, safe: envOneEmptyExample, allowEmptyValues: true }),
oneEmptyResult,
done
)
})
})
describe('Missing a variable', () => {
test('Should load fine (not-safe)', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envMissingOne }),
missingOneResult,
done
)
})
test('Should fail on safe mode (if allowEmptyValues is false)', (done) => {
const config = getConfig(
'web',
new DotenvPlugin({ path: envMissingOne, safe: envMissingOneExample })
)
webpack(config, (err) => {
expect(err.message).toBe('Missing environment variable: TEST')
done()
})
})
})
describe('Silent mode', () => {
test('Should display warning by default', (done) => {
compile(getConfig('web', new DotenvPlugin({ path: false })), () => {
expect(global.console.warn).toHaveBeenCalled()
done()
})
})
test('Should not display warning when silent mode enabled', (done) => {
compile(
getConfig('web', new DotenvPlugin({ path: false, silent: true })),
() => {
expect(global.console.warn).toHaveBeenCalledTimes(0)
done()
}
)
})
})
describe('process.env stubbing', () => {
const expectToBeStubbed = (result) => {
expect(result).toMatch('const TEST = "testing"')
expect(result).toMatch('const TEST2 = "MISSING_ENV_VAR".TEST2')
expect(result).toMatch('const NODE_ENV = "development"')
expect(result).toMatch('const MONGOLAB_USER = "MISSING_ENV_VAR".MONGOLAB_USER')
}
const expectNotToBeStubbed = (result) => {
expect(result).toMatch('const TEST = "testing"')
expect(result).toMatch('const TEST2 = process.env.TEST2')
expect(result).toMatch('const NODE_ENV = "development"')
expect(result).toMatch('const MONGOLAB_USER = process.env.MONGOLAB_USER')
}
const plugin = new DotenvPlugin({ path: envSimple })
const cases = [
['web', true],
[['web'], true],
['es5', true],
['es2020', true],
[['es2020', 'web'], true],
['electron-renderer', true],
['electron9-renderer', true],
['electron-preload', true],
['node', false],
[['node'], false],
['node14', false],
['electron-main', false],
['electron9-main', false],
[['es2020', 'node'], false]
]
test.each(cases)('%s', (target, shouldStub, done) => {
compile(
getConfig(target, plugin),
(result) => {
if (shouldStub) {
expectToBeStubbed(result)
} else {
expectNotToBeStubbed(result)
}
done()
}
)
})
describe('ignoreStub override', () => {
// `ignoreStub == null` case is covered by above test
test('should never stub if set to true', (done) => {
const plugin = new DotenvPlugin({ ignoreStub: true, path: envSimple })
compile(getConfig('web', plugin), (result) => {
expectNotToBeStubbed(result)
compile(getConfig('node', plugin), (result) => {
expectNotToBeStubbed(result)
done()
})
})
})
test('should always stub if set to false', (done) => {
const plugin = new DotenvPlugin({ ignoreStub: false, path: envSimple })
compile(getConfig('web', plugin), (result) => {
expectToBeStubbed(result)
compile(getConfig('node', plugin), (result) => {
expectToBeStubbed(result)
done()
})
})
})
})
})
describe('Alternative prefix', () => {
const prefix = 'META_ENV_'
test('Should include environment variables from .env file in the root dir.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ prefix }),
altDefaultEnvResult,
done
)
})
test('Should include environment variables from provided .env file.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envSimple, prefix }),
altSimpleResult,
done
)
})
test('Should include default environment variables from .env.defaults with .env overrides.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ defaults: true, prefix }),
altDefaultsResult,
done
)
})
test('Should include default environment variables from provided defaults file with .env overrides.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ defaults: envDefaults, prefix }),
altDefaultsResult2,
done
)
})
test('Should include environment variables with empty vars from provided .env file.', (done) => {
expectResultsToContainReplacements(
new DotenvPlugin({ path: envOneEmpty, prefix }),
altOneEmptyResult,
done
)
})
describe('Stubbing when prefix is set', () => {
const notStubbed = [
'const TEST_ALT = "testing"',
'const TEST2_ALT = META_ENV_TEST2',
// Replacement of NODE_ENV to mode, specified in webpack config,
// is inteded behaviour of webpack
// @see https://webpack.js.org/configuration/mode/
'const NODE_ENV = "development"',
'const BASIC = process.env.BASIC',
'const MONGOLAB_USER = process.env.MONGOLAB_USER',
'const MONGOLAB_PORT = process.env.MONGOLAB_PORT'
]
test('Should not stab if prefix is set to value other than process.env', (done) => {
const plugin = new DotenvPlugin({ prefix, path: envSimple })
compile(getConfig('web', plugin), (result) => {
notStubbed.forEach((expectation) => {
expect(result).toMatch(expectation)
})
done()
})
})
})
})
})