All files / enzyme/src Debug.js

84% Statements 21/25
72.73% Branches 24/33
100% Functions 11/11
82.61% Lines 19/23
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                  19x           25x       19x       5x       5x                       19x 19x 19x       32x 22x   19x 19x 19x 19x 19x 19x     19x     19x       1x    
import {
  childrenOfNode,
} from './ShallowTraversal';
import {
  propsOfNode,
} from './Utils';
import { without, escape, compact } from 'underscore';
 
export function typeName(node) {
  return typeof node.type === 'function'
    ? (node.type.displayName || node.type.name || 'Component')
    : node.type;
}
 
export function spaces(n) {
  return Array(n + 1).join(' ');
}
 
export function indent(depth, string) {
  return string.split('\n').map(x => `${spaces(depth)}${x}`).join('\n');
}
 
function propString(prop) {
  switch (typeof prop) {
    case 'function':
      return '{[Function]}';
    case 'string':
      return `"${prop}"`;
    case 'number':
    case 'boolean':
      return `{${prop}}`;
    case 'object':
      return `{{...}}`;
    default:
      return `{[${typeof prop}]}`;
  }
}
 
function propsString(node) {
  const props = propsOfNode(node);
  const keys = without(Object.keys(props), 'children');
  return keys.map(key => `${key}=${propString(props[key])}`).join(' ');
}
 
export function debugNode(node, indentLength = 2) {
  if (typeof node === 'string' || typeof node === 'number') return escape(node);
  if (!node) return '';
 
  const children = compact(childrenOfNode(node).map(n => debugNode(n, indentLength)));
  const type = typeName(node);
  const props = propsString(node);
  const beforeProps = props ? ' ' : '';
  const nodeClose = children.length ? `</${type}>` : '/>';
  const afterProps = children.length
    ? '>'
    : ' ';
  const childrenIndented = children.length
    ? `\n${children.map(x => indent(indentLength, x)).join('\n')}\n`
    : '';
  return `<${type}${beforeProps}${props}${afterProps}${childrenIndented}${nodeClose}`;
}
 
export function debugNodes(nodes) {
  return nodes.map(debugNode).join('\n\n\n');
}