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
})
                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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With