All files / test enzyme-adapter-react-16.js

64.46% Statements 78/121
47.76% Branches 32/67
66.67% Functions 12/18
64.71% Lines 77/119

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                          202x     5x 5x 5x 5x 5x 5x 5x 5x 5x 5x     190x 190x 190x 173x 173x   190x       62x 62x 62x 62x 62x 45x 45x 45x         45x     62x       192x           192x 192x           71x                   27x                     62x 62x 30x   62x                     2x         30x                 128x     128x 128x   128x 128x                     2x 2x     2x         2x     2x         5x 5x           19x 19x 19x 19x   19x 19x 19x         19x 19x               2x 2x     21x                                         5x 5x 5x 5x   5x   5x     5x 5x             42x     42x 42x                                                                                                                       24x   19x   5x                                               2x                        
/* eslint-disable */
import React from 'react'
import ReactDOM from 'react-dom'
import ReactDOMServer from 'react-dom/server'
import ShallowRenderer from 'react-test-renderer/shallow'
import TestUtils from 'react-dom/test-utils'
import { EnzymeAdapter } from 'enzyme'
import {
  elementToTree,
  nodeTypeFromType,
  mapNativeEventNames,
  propFromEvent,
  assertDomAvailable,
  withSetStateAllowed,
  createRenderWrapper,
  createMountWrapper,
  propsWithKeysAndRef,
} from 'enzyme-adapter-utils'
import { findCurrentFiberUsingSlowPath } from 'react-reconciler/reflection'
 
function ensureKeyOrUndefined(key) {
  return key || (key === '' ? '' : undefined);
}
 
const HostRoot = 3
const ClassComponent = 2
const Fragment = 10
const FunctionalComponent = 1
const HostPortal = 4
const HostComponent = 5
const HostText = 6
const Mode = 11
const ContextConsumer = 12
const ContextProvider = 13
 
function nodeAndSiblingsArray(nodeWithSibling) {
  const array = []
  let node = nodeWithSibling
  while (node != null) {
    array.push(node)
    node = node.sibling
  }
  return array
}
 
function flatten(arr) {
  const result = []
  const stack = [{ i: 0, array: arr }]
  while (stack.length) {
    const n = stack.pop()
    while (n.i < n.array.length) {
      const el = n.array[n.i]
      n.i += 1
      Iif (Array.isArray(el)) {
        stack.push(n)
        stack.push({ i: 0, array: el })
        break
      }
      result.push(el)
    }
  }
  return result
}
 
function toTree(vnode) {
  Iif (vnode == null) {
    return null
  }
  // TODO(lmr): I'm not really sure I understand whether or not this is what
  // i should be doing, or if this is a hack for something i'm doing wrong
  // somewhere else. Should talk to sebastian about this perhaps
  const node = findCurrentFiberUsingSlowPath(vnode)
  switch (node.tag) {
    case HostRoot: // 3
      return toTree(node.child)
    case HostPortal: // 4
      return toTree(node.child)
    case ClassComponent:
      return {
        nodeType: 'class',
        type: node.type,
        props: { ...node.memoizedProps },
        key: ensureKeyOrUndefined(node.key),
        ref: node.ref,
        instance: node.stateNode,
        rendered: childrenToTree(node.child),
      }
    case FunctionalComponent: // 1
      return {
        nodeType: 'function',
        type: node.type,
        props: { ...node.memoizedProps },
        key: ensureKeyOrUndefined(node.key),
        ref: node.ref,
        instance: null,
        rendered: childrenToTree(node.child),
      }
    case HostComponent: {
      // 5
      let renderedNodes = flatten(nodeAndSiblingsArray(node.child).map(toTree))
      if (renderedNodes.length === 0) {
        renderedNodes = [node.memoizedProps.children]
      }
      return {
        nodeType: 'host',
        type: node.type,
        props: { ...node.memoizedProps },
        key: ensureKeyOrUndefined(node.key),
        ref: node.ref,
        instance: node.stateNode,
        rendered: renderedNodes,
      }
    }
    case HostText: // 6
      return node.memoizedProps
    case Fragment: // 10
    case Mode: // 11
    case ContextProvider: // 13
    case ContextConsumer: // 12
      return childrenToTree(node.child)
    default:
      throw new Error(
        `Enzyme Internal Error: unknown node with tag ${node.tag}`,
      )
  }
}
 
function childrenToTree(node) {
  Iif (!node) {
    return null
  }
  const children = nodeAndSiblingsArray(node)
  Iif (children.length === 0) {
    return null
  } else Eif (children.length === 1) {
    return toTree(children[0])
  }
  return flatten(children.map(toTree))
}
 
function nodeToHostNode(_node) {
  // NOTE(lmr): node could be a function component
  // which wont have an instance prop, but we can get the
  // host node associated with its return value at that point.
  // Although this breaks down if the return value is an array,
  // as is possible with React 16.
  let node = _node
  while (node && !Array.isArray(node) && node.instance === null) {
    node = node.rendered
  }
  Iif (Array.isArray(node)) {
    // TODO(lmr): throw warning regarding not being able to get a host node here
    throw new Error('Trying to get host node of an array')
  }
  // if the SFC returned null effectively, there is no host node.
  Iif (!node) {
    return null
  }
  return ReactDOM.findDOMNode(node.instance)
}
 
class ReactSixteenAdapter extends EnzymeAdapter {
  constructor() {
    super()
    this.options = {
      ...this.options,
      enableComponentDidUpdateOnSetState: true,
    }
  }
  createMountRenderer(options) {
    assertDomAvailable('mount')
    const domNode = options.attachTo || global.document.createElement('div')
    let instance = null
    return {
      render(el, context, callback) {
        Eif (instance === null) {
          const ReactWrapperComponent = createMountWrapper(el, options)
          const wrappedEl = React.createElement(ReactWrapperComponent, {
            Component: el.type,
            props: el.props,
            context,
          })
          instance = ReactDOM.render(wrappedEl, domNode)
          Iif (typeof callback === 'function') {
            callback()
          }
        } else {
          instance.setChildProps(el.props, context, callback)
        }
      },
      unmount() {
        ReactDOM.unmountComponentAtNode(domNode)
        instance = null
      },
      getNode() {
        return instance ? toTree(instance._reactInternalFiber).rendered : null
      },
      simulateEvent(node, event, mock) {
        const mappedEvent = mapNativeEventNames(event)
        const eventFn = TestUtils.Simulate[mappedEvent]
        if (!eventFn) {
          throw new TypeError(
            `ReactWrapper::simulate() event '${event}' does not exist`,
          )
        }
        // eslint-disable-next-line react/no-find-dom-node
        eventFn(nodeToHostNode(node), mock)
      },
      batchedUpdates(fn) {
        return fn()
        // return ReactDOM.unstable_batchedUpdates(fn);
      },
    }
  }
 
  createShallowRenderer(/* options */) {
    const renderer = new ShallowRenderer()
    let isDOM = false
    let cachedNode = null
    return {
      render(el, context) {
        cachedNode = el
        /* eslint consistent-return: 0 */
        Iif (typeof el.type === 'string') {
          isDOM = true
        } else {
          isDOM = false
          return withSetStateAllowed(() => renderer.render(el, context))
        }
      },
      unmount() {
        renderer.unmount()
      },
      getNode() {
        Iif (isDOM) {
          return elementToTree(cachedNode)
        }
        const output = renderer.getRenderOutput()
        return {
          nodeType: nodeTypeFromType(cachedNode.type),
          type: cachedNode.type,
          props: cachedNode.props,
          key: ensureKeyOrUndefined(cachedNode.key),
          ref: cachedNode.ref,
          instance: renderer._instance,
          rendered: Array.isArray(output)
            ? flatten(output).map(elementToTree)
            : elementToTree(output),
        }
      },
      simulateEvent(node, event, ...args) {
        const handler = node.props[propFromEvent(event)]
        if (handler) {
          withSetStateAllowed(() => {
            // TODO(lmr): create/use synthetic events
            // TODO(lmr): emulate React's event propagation
            // ReactDOM.unstable_batchedUpdates(() => {
            handler(...args)
            // });
          })
        }
      },
      batchedUpdates(fn) {
        return fn()
        // return ReactDOM.unstable_batchedUpdates(fn);
      },
    }
  }
 
  createStringRenderer(options) {
    return {
      render(el, context) {
        if (
          options.context &&
          (el.type.contextTypes || options.childContextTypes)
        ) {
          const childContextTypes = {
            ...(el.type.contextTypes || {}),
            ...options.childContextTypes,
          }
          const ContextWrapper = createRenderWrapper(
            el,
            context,
            childContextTypes,
          )
          return ReactDOMServer.renderToStaticMarkup(
            React.createElement(ContextWrapper),
          )
        }
        return ReactDOMServer.renderToStaticMarkup(el)
      },
    }
  }
 
  // Provided a bag of options, return an `EnzymeRenderer`. Some options can be implementation
  // specific, like `attach` etc. for React, but not part of this interface explicitly.
  // eslint-disable-next-line class-methods-use-this, no-unused-vars
  createRenderer(options) {
    switch (options.mode) {
      case EnzymeAdapter.MODES.MOUNT:
        return this.createMountRenderer(options)
      case EnzymeAdapter.MODES.SHALLOW:
        return this.createShallowRenderer(options)
      case EnzymeAdapter.MODES.STRING:
        return this.createStringRenderer(options)
      default:
        throw new Error(
          `Enzyme Internal Error: Unrecognized mode: ${options.mode}`,
        )
    }
  }
 
  // converts an RSTNode to the corresponding JSX Pragma Element. This will be needed
  // in order to implement the `Wrapper.mount()` and `Wrapper.shallow()` methods, but should
  // be pretty straightforward for people to implement.
  // eslint-disable-next-line class-methods-use-this, no-unused-vars
  nodeToElement(node) {
    if (!node || typeof node !== 'object') return null
    return React.createElement(node.type, propsWithKeysAndRef(node))
  }
 
  elementToNode(element) {
    return elementToTree(element)
  }
 
  nodeToHostNode(node) {
    return nodeToHostNode(node)
  }
 
  isValidElement(element) {
    return React.isValidElement(element)
  }
 
  createElement(...args) {
    return React.createElement(...args)
  }
}
 
export default ReactSixteenAdapter