11

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
})
6

3 Answers 3

13

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
2
  • 3
    dive() doesn't work for React.Fragment: TypeError: ShallowWrapper::dive() can only be called on components May 7, 2019 at 17:35
  • 1
    Use shallow() when there are multiple children.
    – tafaust
    Apr 14, 2020 at 5:28
3

for me this worked

const wrapper = shallow(<ConnectedComponent />).childAt(0).dive(); 
console.log(wrapper.instance());
0

When I use this code

const wrapper = shallow(<ConnectedComponent />).childAt(0).dive(); 
console.log(wrapper.instance());

I am getting this error:

TypeError: ShallowWrapper::dive() can not be called on Host Components

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.