Testing React Component with Jest/Enzyme

只愿长相守 提交于 2020-01-02 08:02:32

问题


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:


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.



来源:https://stackoverflow.com/questions/39854162/testing-react-component-with-jest-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!