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?

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
Varsha
  • 53
  • 6
  • 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? – Alexandr Lazarev Oct 04 '16 at 14:37

1 Answers1

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.

Kryten
  • 15,230
  • 6
  • 45
  • 68