Enzyme: wrapper.instance() returns null under React 16

Created on 11 Oct 2017  路  7Comments  路  Source: enzymejs/enzyme

To reproduce:

npm install [email protected] [email protected] [email protected] [email protected] [email protected]

Then create test.js:

const React = require('react');
const {shallow, configure} = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

configure({adapter: new Adapter()});

const wrapper = shallow(React.createElement('div', null, 'Hello World'));
console.log(wrapper.instance());

And finally:

node test.js

We expect this to print something exciting, instead it just prints 'null'.

package 16 v3 expected difference

Most helpful comment

How do we use enzyme to test a functional component? Is there a different way?

All 7 comments

SFCs and host nodes don't have instances in React 16.

This isn't in the migration guide (because it's React 16-related, not enzyme 3 related) - #1243 will address this by documenting the difference.

Edit: Nevermind - I figured out my issue. :P

If someone else runs into this, you want to replace getNode() from earlier enzymes with getElement().

Ah. I see where I went wrong. One of my mount() tests was complaining that I should use instance() instead of getNode(), but this is only true for mount() and not for shallow().

My solution was different, but I'll share to hopefully help someone else.

I'm silly, and was using .dive():

const wrapper = shallow(<MyComponent />).dive();

for a dumb component.

All I had to do was NOT use .dive(), and it worked :)

Hopefully my mistake can help guide someone

Any my mistake was calling it on a functional component :)

How do we use enzyme to test a functional component? Is there a different way?

@blu3printchris you don't need the instance to test any component, really - you wrap it, you pass it props, and you assert on what it renders.

Was this page helpful?
0 / 5 - 0 ratings