helper.js
2.34 KB
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
/* eslint-env jest */
import getProp from '../src/getProp';
const nodeVersion = parseInt(process.version.match(/^v(\d+)\./)[1], 10);
export const fallbackToBabylon = nodeVersion < 6;
let parserName;
const babelParser = fallbackToBabylon ? require('babylon') : require('@babel/parser');
const flowParser = require('flow-parser');
const defaultPlugins = [
'jsx',
'functionBind',
'estree',
'objectRestSpread',
'optionalChaining',
// 'nullishCoalescing', // TODO: update to babel 7
];
let plugins = [...defaultPlugins];
export function setParserName(name) {
parserName = name;
}
export function changePlugins(pluginOrFn) {
if (Array.isArray(pluginOrFn)) {
plugins = pluginOrFn;
} else if (typeof pluginOrFn === 'function') {
plugins = pluginOrFn(plugins);
} else {
throw new Error('changePlugins argument should be either an array or a function');
}
}
beforeEach(() => {
plugins = [...defaultPlugins];
});
function parse(code) {
if (parserName === undefined) {
throw new Error('No parser specified');
}
if (parserName === 'babel') {
try {
return babelParser.parse(code, { plugins, sourceFilename: 'test.js' });
} catch (_) {
// eslint-disable-next-line no-console
console.warn(`Failed to parse with ${fallbackToBabylon ? 'babylon' : 'Babel'} parser.`);
}
}
if (parserName === 'flow') {
try {
return flowParser.parse(code, { plugins });
} catch (_) {
// eslint-disable-next-line no-console
console.warn('Failed to parse with the Flow parser');
}
}
throw new Error(`The parser ${parserName} is not yet supported for testing.`);
}
export function getOpeningElement(code) {
const parsedCode = parse(code);
let body;
if (parsedCode.program) {
// eslint-disable-next-line prefer-destructuring
body = parsedCode.program.body;
} else {
// eslint-disable-next-line prefer-destructuring
body = parsedCode.body;
}
if (Array.isArray(body) && body[0] != null) {
const [{ expression }] = body;
return expression.type === 'JSXFragment' ? expression.openingFragment : expression.openingElement;
}
return null;
}
export function extractProp(code, prop = 'foo') {
const node = getOpeningElement(code);
const { attributes: props } = node;
return getProp(props, prop);
}
export const describeIfNotBabylon = fallbackToBabylon ? describe.skip : describe;