10
votes

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
})
1
Have you try using dive() and not instance()?Paolo Dell'Aguzzo
I get myComp.dive is not a function, also can't find the dive function in the ReactWrapper api here: github.com/airbnb/enzyme/blob/master/docs/api/mount.mdFuseques
Maybe this issue can help you github.com/airbnb/enzyme/issues/1002Paolo Dell'Aguzzo
i read it before opening this topic, thanks anywayFuseques
Have you tried getting it by name instead of by the variable itself? const myComp = wrapper.find('NonConnectedComponent') (note the quotes around the name). Not the most beautiful solution, but good for workaround if works.András Geiszl

1 Answers

11
votes

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