3

I am trying to use Enzyme's shallow wrapper to get the instance of my component and calling my class function over it. It shows me this error: TypeError: tree.instance(...).onCampaignSelected is not a function

class ToolbarPage extends Component {
  constructor(){
    super();
    this.onCampaignSelected = this.onCampaignSelected.bind(this);
    this.state = {
      item: null
    }
  }

  onCampaignSelected (item) {
     this.setState({item})
  }

  render () {
    return (
      <MyComponent onItemSelected={this.onCampaignSelected} />
    )
  }
}
function mapStateToProps(state){
  buttons: state.toolbar.buttons
}
export default connect(mapStateToProps)(ToolbarPage);

My test case looks like this

import { shallow, mount } from 'enzyme';
import ToolbarPage from './ToolbarPage';
import configureStore from 'configureStore';

const store = configureStore();

const props = {
 store,
 isLoggedIn: false,
 messageCounter: 0
}

describe('<ToolbarPage />', () => {
  it('allows to select campaign', () => {
    const tree = shallow(<ToolbarPage {...props}/>);
    tree.instance().onCampaignSelected();
  })
})

I also figured out that it is a wrapped component, so I won't get this function on the wrapped component. How do I access this function?

1
  • The code seems to be ok. What does tree.debug() return?. Also, don't you get error that props are undefined? Didn't you miss something in the provided code sample? Commented Oct 4, 2016 at 14:37

1 Answer 1

0

shallow does not render the full set of components with all of their properties & methods. It is intended for basic "did this thing render what I expected?" testing.

mount will give you everything and should allow you to test whatever you need. It is very useful for testing event handling & manipulating the state of components to test the interactions between components.

Sign up to request clarification or add additional context in comments.

1 Comment

It should let you call instance methods though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.