Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enzyme wrapper.instance() is null for connected component

I am trying to test a connected react component, however once wrapping it, I cannot get the instance of it using instance(), it returns null. for non-connected components it does return the instance, what is the difference and how can i get an instance of a connected component?

it('connected component', () => {
  const wrapper = mount(
    <Provider store={store}>
      <BrowserRouter>
        <ConnectedComponent />
      </BrowserRouter>
    </Provider>
  )
  const myComp = wrapper.find(ConnectedComponent)
  expect(myComp).toHaveLength(1) // passes
  console.log(myComp.instance()) //null

})

it('non-connected component', () => {
  const wrapper = mount(
    <Provider store={store}>
      <BrowserRouter>
        <NonConnectedComponent />
      </BrowserRouter>
    </Provider>
  )
  const myComp = wrapper.find(NonConnectedComponent)
  expect(myComp).toHaveLength(1) // passes
  console.log(myComp.instance()) // prints the instancce
})
like image 659
Fuseques Avatar asked Jul 04 '18 11:07

Fuseques


People also ask

What does wrapper instance () do?

instance() => ReactComponent. Returns the single-node wrapper's node's underlying class instance; this in its methods. It must be a single-node wrapper. NOTE: With React 16 and above, instance() returns null for stateless functional components.


1 Answers

The issue is that for connected components you export the Connect wrapper, not the component itself. There are a few options to deal with it.

Option 1. Use dive(). Note that this is available only when you use shallow rendering and will not be available on mount.

const component = shallow(<ConnectedComponent />).dive(); // dive one level into the Connect wrapper
component.instance(); // the instance will be available

Option 2. Export your component separately before connecting it and use named import to get it.

// in your component
export class MyComponent extends React.Component {
  ...
}

export default connect()(MyComponent);

// in your tests
import { MyComponent } from './component'; // this will get you non-default export of the component, which is not connected
like image 103
Igor Skoldin Avatar answered Sep 22 '22 15:09

Igor Skoldin