helper.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* eslint-env jest */
  2. import getProp from '../src/getProp';
  3. const nodeVersion = parseInt(process.version.match(/^v(\d+)\./)[1], 10);
  4. export const fallbackToBabylon = nodeVersion < 6;
  5. let parserName;
  6. const babelParser = fallbackToBabylon ? require('babylon') : require('@babel/parser');
  7. const flowParser = require('flow-parser');
  8. const defaultPlugins = [
  9. 'jsx',
  10. 'functionBind',
  11. 'estree',
  12. 'objectRestSpread',
  13. 'optionalChaining',
  14. // 'nullishCoalescing', // TODO: update to babel 7
  15. ];
  16. let plugins = [...defaultPlugins];
  17. export function setParserName(name) {
  18. parserName = name;
  19. }
  20. export function changePlugins(pluginOrFn) {
  21. if (Array.isArray(pluginOrFn)) {
  22. plugins = pluginOrFn;
  23. } else if (typeof pluginOrFn === 'function') {
  24. plugins = pluginOrFn(plugins);
  25. } else {
  26. throw new Error('changePlugins argument should be either an array or a function');
  27. }
  28. }
  29. beforeEach(() => {
  30. plugins = [...defaultPlugins];
  31. });
  32. function parse(code) {
  33. if (parserName === undefined) {
  34. throw new Error('No parser specified');
  35. }
  36. if (parserName === 'babel') {
  37. try {
  38. return babelParser.parse(code, { plugins, sourceFilename: 'test.js' });
  39. } catch (_) {
  40. // eslint-disable-next-line no-console
  41. console.warn(`Failed to parse with ${fallbackToBabylon ? 'babylon' : 'Babel'} parser.`);
  42. }
  43. }
  44. if (parserName === 'flow') {
  45. try {
  46. return flowParser.parse(code, { plugins });
  47. } catch (_) {
  48. // eslint-disable-next-line no-console
  49. console.warn('Failed to parse with the Flow parser');
  50. }
  51. }
  52. throw new Error(`The parser ${parserName} is not yet supported for testing.`);
  53. }
  54. export function getOpeningElement(code) {
  55. const parsedCode = parse(code);
  56. let body;
  57. if (parsedCode.program) {
  58. // eslint-disable-next-line prefer-destructuring
  59. body = parsedCode.program.body;
  60. } else {
  61. // eslint-disable-next-line prefer-destructuring
  62. body = parsedCode.body;
  63. }
  64. if (Array.isArray(body) && body[0] != null) {
  65. const [{ expression }] = body;
  66. return expression.type === 'JSXFragment' ? expression.openingFragment : expression.openingElement;
  67. }
  68. return null;
  69. }
  70. export function extractProp(code, prop = 'foo') {
  71. const node = getOpeningElement(code);
  72. const { attributes: props } = node;
  73. return getProp(props, prop);
  74. }
  75. export const describeIfNotBabylon = fallbackToBabylon ? describe.skip : describe;