-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
84 lines (64 loc) · 2.12 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
import test from 'ava'
import mockery from 'mockery'
const mock = setupMock()
const plugin = require('./index')
test('No parameters', noOpMacro)
test('Empty array', noOpMacro, [])
test('Empty string', noOpMacro, '')
test('Single parameter', successMacro, {
URL: 'http://url.com'
}, 'URL')
test('Multiple, comma-separated parameters', successMacro, {
URL: 'http://url.com',
KEY: '123abc'
}, 'URL', 'KEY')
test('Single value in an array parameter', successMacro, {
URL: 'http://url.com'
}, ['URL'])
test('Multiple values in an array parameter', successMacro, {
URL: 'http://url.com',
KEY: '123abc'
}, ['URL', 'KEY'])
test('Throws when the env var is not defined', failureMacro, {
KEY: ''
})
test('Throws when one of multiple env vars is not defined', failureMacro, {
URL: '',
KEY: '123abc'
})
test('Throws when none of multiple env vars is defined', failureMacro, {
URL: '',
KEY: ''
})
function setupMock() {
mockery.enable()
mockery.registerAllowable('./index')
const mock = { DefinePlugin: function() {} }
mockery.registerMock('webpack', mock)
return mock
}
const prepareMockedModule = definePluginMock => {
mock.DefinePlugin = definePluginMock
return plugin
}
const setEnvVars = envVarsMap => Object.keys(envVarsMap).forEach(envVar => process.env[envVar] = envVarsMap[envVar])
function noOpMacro(t, ...pluginParameters) {
t.plan(0)
prepareMockedModule(function() {
t.fail()
})(...pluginParameters)
}
function successMacro(t, envVarsMap, ...pluginParameters) {
setEnvVars(envVarsMap)
prepareMockedModule(function(definePluginParameter) {
t.deepEqual(definePluginParameter, {
'process.env': Object.keys(envVarsMap).reduce((memo, envVar) => Object.assign(memo, { [envVar]: JSON.stringify(process.env[envVar]) }), {})
})
})(...pluginParameters)
}
function failureMacro(t, envVarsMap) {
setEnvVars(envVarsMap)
const errorMessageRegExp = new RegExp(Object.keys(envVarsMap).join('|'))
t.throws(() => prepareMockedModule(function() {})(...Object.keys(envVarsMap)), errorMessageRegExp)
t.throws(() => prepareMockedModule(function() {})(Object.keys(envVarsMap)), errorMessageRegExp)
}