-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathindex.js
498 lines (482 loc) · 13.9 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
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
import path from 'path'
import {cosmiconfigSync as cosmiconfigSyncMock} from 'cosmiconfig'
import cpy from 'cpy'
import babel from '@babel/core'
import pluginTester from 'babel-plugin-tester'
import plugin from '../'
const projectRoot = path.join(__dirname, '../../')
jest.mock('cosmiconfig', () => {
const cosmiconfigExports = jest.requireActual('cosmiconfig')
const actualCosmiconfigSync = cosmiconfigExports.cosmiconfigSync
function fakeCosmiconfigSync(...args) {
fakeCosmiconfigSync.explorer = actualCosmiconfigSync(...args)
return fakeCosmiconfigSync.explorer
}
return {...cosmiconfigExports, cosmiconfigSync: fakeCosmiconfigSync}
})
beforeAll(() => {
// copy our mock modules to the node_modules directory
// so we can test how things work when importing a macro
// from the node_modules directory.
return cpy(['**/*.js'], path.join('..', '..', 'node_modules'), {
parents: true,
cwd: path.join(projectRoot, 'other', 'mock-modules'),
})
})
beforeEach(() => {
jest.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
console.error.mockRestore()
jest.clearAllMocks()
})
expect.addSnapshotSerializer({
print(val) {
return (
val
.split(projectRoot)
.join('<PROJECT_ROOT>/')
.replace(/\\/g, '/')
// Remove the path of file which thrown an error
.replace(/Error:[^:]*:/, 'Error:')
)
},
test(val) {
return typeof val === 'string'
},
})
pluginTester({
plugin,
snapshot: true,
babelOptions: {
filename: __filename,
parserOpts: {
plugins: ['jsx'],
},
generatorOpts: {quotes: 'double'},
},
tests: [
{
title: 'does nothing to code that does not import macro',
snapshot: false,
code: `
import foo from './some-file-without-macro'
const bar = require('./some-other-file-without-macro')
`,
},
{
title: 'does nothing but remove macros if it is unused',
snapshot: true,
code: `
import foo from "./fixtures/eval.macro";
const bar = 42;
`,
},
{
title: 'raises an error if macro does not exist',
error: true,
code: `
import foo from './some-macros-that-doesnt-even-need-to-exist.macro'
export default 'something else'
`,
},
{
title: 'works with import',
code: `
import myEval from './fixtures/eval.macro'
const x = myEval\`34 + 45\`
`,
},
{
title: 'works with require',
code: `
const evaler = require('./fixtures/eval.macro')
const x = evaler\`34 + 45\`
`,
},
{
title: 'works with require destructuring',
code: `
const {css, styled} = require('./fixtures/emotion.macro')
const red = css\`
background-color: red;
\`
const Div = styled.div\`
composes: \${red}
color: blue;
\`
`,
},
{
title: 'works with require destructuring and aliasing',
code: `
const {css: CSS, styled: STYLED} = require('./fixtures/emotion.macro')
const red = CSS\`
background-color: red;
\`
const Div = STYLED.div\`
composes: \${red}
color: blue;
\`
`,
},
{
title: 'works with function calls',
code: `
import myEval from './fixtures/eval.macro'
const x = myEval('34 + 45')
`,
},
{
title: 'Works as a JSXElement',
code: `
import MyEval from './fixtures/eval.macro'
const x = <MyEval>34 + 45</MyEval>
`,
},
{
title: 'Supports named imports',
code: `
import {css as CSS, styled as STYLED} from './fixtures/emotion.macro'
const red = CSS\`
background-color: red;
\`
const Div = STYLED.div\`
composes: \${red}
color: blue;
\`
`,
},
{
title: 'supports compiled macros (`__esModule` + `export default`)',
code: `
import {css, styled} from './fixtures/emotion-esm.macro'
const red = css\`
background-color: red;
\`
const Div = styled.div\`
composes: \${red}
color: blue;
\`
`,
},
{
title: 'supports macros from node_modules',
code: `
import fakeMacro from 'babel-plugin-macros-test-fake/macro'
fakeMacro('hi')
`,
teardown() {
try {
// kinda abusing the babel-plugin-tester API here
// to make an extra assertion
// eslint-disable-next-line
const fakeMacro = require('babel-plugin-macros-test-fake/macro')
expect(fakeMacro.innerFn).toHaveBeenCalledTimes(1)
expect(fakeMacro.innerFn).toHaveBeenCalledWith({
references: expect.any(Object),
source: expect.stringContaining(
'babel-plugin-macros-test-fake/macro',
),
state: expect.any(Object),
babel: expect.any(Object),
isBabelMacrosCall: true,
})
expect(fakeMacro.innerFn.mock.calls[0].babel).toBe(babel)
} catch (e) {
console.error(e)
throw e
}
},
},
{
title: 'supports macros from node_modules with scope',
code: `
import fakeMacro from '@scope/package/macro'
fakeMacro('hi')
`,
teardown() {
try {
// kinda abusing the babel-plugin-tester API here
// to make an extra assertion
// eslint-disable-next-line
const fakeMacro = require('@scope/package/macro')
expect(fakeMacro.innerFn).toHaveBeenCalledTimes(1)
expect(fakeMacro.innerFn).toHaveBeenCalledWith({
references: expect.any(Object),
source: expect.stringContaining('@scope/package/macro'),
state: expect.any(Object),
babel: expect.any(Object),
isBabelMacrosCall: true,
})
expect(fakeMacro.innerFn.mock.calls[0].babel).toBe(babel)
} catch (e) {
console.error(e)
throw e
}
},
},
{
title: 'optionally keep imports (variable assignment)',
code: `
const macro = require('./fixtures/keep-imports.macro')
const red = macro('noop');
`,
},
{
title: 'optionally keep imports (import declaration)',
code: `
import macro from './fixtures/keep-imports.macro'
const red = macro('noop');
`,
},
{
title:
'optionally keep imports in combination with babel-preset-env (#80)',
code: `
import macro from './fixtures/keep-imports.macro'
const red = macro('noop')
`,
babelOptions: {
plugins: [
require.resolve('babel-plugin-transform-es2015-modules-commonjs'),
],
},
},
{
title: 'throws an error if the macro is not properly wrapped',
error: true,
code: `
import unwrapped from './fixtures/non-wrapped.macro'
unwrapped('hey')
`,
},
{
title: 'forwards MacroErrors thrown by the macro',
error: true,
code: `
import errorThrower from './fixtures/macro-error-thrower.macro'
errorThrower('hey')
`,
},
{
title: 'prepends the relative path for errors thrown by the macro',
error: true,
code: `
import errorThrower from './fixtures/error-thrower.macro'
errorThrower('hey')
`,
},
{
title: 'appends the npm URL for errors thrown by node modules',
error: true,
code: `
import errorThrower from 'babel-plugin-macros-test-error-thrower.macro'
errorThrower('hi')
`,
},
{
title:
'appends the npm URL for errors thrown by node modules with a slash',
error: true,
code: `
import errorThrower from 'babel-plugin-macros-test-error-thrower/macro'
errorThrower('hi')
`,
},
{
title: 'macros can set their configName and get their config',
fixture: path.join(__dirname, 'fixtures/config/code.js'),
teardown() {
try {
const babelMacrosConfig = require('./fixtures/config/babel-plugin-macros.config')
const configurableMacro = require('./fixtures/config/configurable.macro')
expect(configurableMacro.realMacro).toHaveBeenCalledTimes(1)
expect(configurableMacro.realMacro.mock.calls[0][0].config).toEqual(
babelMacrosConfig[configurableMacro.configName],
)
configurableMacro.realMacro.mockClear()
} catch (e) {
console.error(e)
throw e
}
},
},
{
title:
'when there is an error reading the config, a helpful message is logged',
error: true,
fixture: path.join(__dirname, 'fixtures/config/code.js'),
setup() {
jest
.spyOn(cosmiconfigSyncMock.explorer, 'search')
.mockImplementationOnce(() => {
throw new Error('this is a cosmiconfig error')
})
jest.spyOn(console, 'error').mockImplementationOnce(() => {})
return function teardown() {
try {
expect(console.error).toHaveBeenCalledTimes(1)
expect(console.error.mock.calls[0]).toMatchSnapshot()
console.error.mockClear()
} catch (e) {
console.error(e)
console.error.mockClear()
throw e
}
}
},
},
{
title: 'when there is no config to load, then no config is passed',
fixture: path.join(__dirname, 'fixtures/config/code.js'),
setup() {
jest
.spyOn(cosmiconfigSyncMock.explorer, 'search')
.mockImplementationOnce(() => {
return null
})
return function teardown() {
try {
const configurableMacro = require('./fixtures/config/configurable.macro')
expect(configurableMacro.realMacro).toHaveBeenCalledTimes(1)
expect(configurableMacro.realMacro.mock.calls[0][0].config).toEqual(
{},
)
configurableMacro.realMacro.mockClear()
} catch (e) {
console.error(e)
throw e
}
}
},
},
{
title: 'when configuration is specified in plugin options',
pluginOptions: {
configurableMacro: {
someConfig: false,
somePluginConfig: true,
},
},
fixture: path.join(__dirname, 'fixtures/config/code.js'),
teardown() {
try {
const configurableMacro = require('./fixtures/config/configurable.macro')
expect(configurableMacro.realMacro).toHaveBeenCalledTimes(1)
expect(configurableMacro.realMacro.mock.calls[0][0].config).toEqual({
fileConfig: true,
someConfig: true,
somePluginConfig: true,
})
configurableMacro.realMacro.mockClear()
} catch (e) {
console.error(e)
throw e
}
},
},
{
title: 'when configuration is specified in plugin options',
pluginOptions: {
configurableMacro: {
someConfig: false,
somePluginConfig: true,
},
},
fixture: path.join(__dirname, 'fixtures/config/cjs-code.js'),
teardown() {
try {
const configurableMacro = require('./fixtures/config/configurable.macro')
expect(configurableMacro.realMacro).toHaveBeenCalledTimes(1)
expect(configurableMacro.realMacro.mock.calls[0][0].config).toEqual({
fileConfig: true,
someConfig: true,
somePluginConfig: true,
})
configurableMacro.realMacro.mockClear()
} catch (e) {
console.error(e)
throw e
}
},
},
{
title: 'when configuration is specified incorrectly in plugin options',
fixture: path.join(__dirname, 'fixtures/config/code.js'),
pluginOptions: {
configurableMacro: 2,
},
teardown() {
try {
const configurableMacro = require('./fixtures/config/configurable.macro')
expect(configurableMacro.realMacro).toHaveBeenCalledTimes(1)
expect(configurableMacro.realMacro).not.toHaveBeenCalledWith(
expect.objectContaining({
config: expect.any,
}),
)
configurableMacro.realMacro.mockClear()
} catch (e) {
console.error(e)
throw e
}
},
},
{
title: 'when a custom isMacrosName option is used on a import',
pluginOptions: {
isMacrosName(v) {
return v.endsWith('-macro.js')
},
},
code: `
import myEval from './fixtures/eval-macro.js'
const x = myEval\`34 + 45\`
`,
},
{
title: 'when a custom isMacrosName option is used on a require',
pluginOptions: {
isMacrosName(v) {
return v.endsWith('-macro.js')
},
},
code: `
const evaler = require('./fixtures/eval-macro.js')
const x = evaler\`34 + 45\`
`,
},
{
title:
'when plugin options configuration cannot be merged with file configuration',
error: true,
fixture: path.join(__dirname, 'fixtures/primitive-config/code.js'),
pluginOptions: {
configurableMacro: {},
},
},
{
title:
'when a plugin that replaces paths is used, macros still work properly',
fixture: path.join(
__dirname,
'fixtures/path-replace-issue/variable-assignment.js',
),
babelOptions: {
babelrc: true,
},
},
{
title: 'Macros are applied in the order respecting plugins order',
code: `
import Wrap from "./fixtures/jsx-id-prefix.macro";
const bar = Wrap(<div id="d1"><p id="p1"></p></div>);
`,
babelOptions: {
presets: [{plugins: [require('./fixtures/jsx-id-prefix.plugin')]}],
},
},
],
})
/* eslint no-console:0 */