React-native-testing-library: HOC - Can't access .root on unmounted test renderer

Created on 10 Nov 2019  路  3Comments  路  Source: callstack/react-native-testing-library

I've a logging HOC:

export const hasLogger = (prefix = '') => WrappedComponent => {
  const HasLogger = props => {
    console.log(`${prefix}[Props]:`, props)
    return <WrappedComponent {...props} />
  }

and a simple component

export const SomeComponent2 = props => <Text>{props.x + props.y}</Text>

While I am still thinking on the best way to validate it, but the test crashes at the render level itself:
with an error "Can't access .root on unmounted test renderer"

describe('HoC component', () => {
  it('logs  props with withlogging', () => {
    const { getByText } = render(hasLogger('')(<SomeComponent2 x={4} y={7} />))
  })
})

Any thoughts on a mistake I'm making or it's a library issue?

question

Most helpful comment

The issue is what you pass to render:

render(hasLogger('')(<SomeComponent2 x={4} y={7} />))

A typical HOC (and yours as well) expects a React Component (SomeComponent), not React Element (<SomeComponent />) which you pass. render on the other hand expects React Element.

To fix this, pass a component to your hasLogger HOC and an element to render:

const ComponentWithLogger = hasLogger()(SomeComponent);
render(<ComponentWithLogger x={4} y={7} />)

All 3 comments

You don't return anything from the hasLogger HOC

Sorry, I missed to copy last two lines:

export const hasLogger = (prefix = '') => WrappedComponent => {
  const HasLogger = props => {
    console.log(`${prefix}[Props]:`, props)
    return <WrappedComponent {...props} />
  }

  return HasLogger
}

The issue is what you pass to render:

render(hasLogger('')(<SomeComponent2 x={4} y={7} />))

A typical HOC (and yours as well) expects a React Component (SomeComponent), not React Element (<SomeComponent />) which you pass. render on the other hand expects React Element.

To fix this, pass a component to your hasLogger HOC and an element to render:

const ComponentWithLogger = hasLogger()(SomeComponent);
render(<ComponentWithLogger x={4} y={7} />)
Was this page helpful?
0 / 5 - 0 ratings