用Jest / Enzyme测试反应组分

时间:2016-10-04 13:53:43

标签: reactjs jestjs enzyme

我正在尝试使用Enzyme的浅层包装器来获取我的组件的实例并调用我的类函数。它向我显示了这个错误: TypeError:tree.instance(...)。onCampaignSelected不是函数

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);

我的测试用例看起来像这样

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();
  })
})

我还发现它是一个包装组件,因此我不会在包装组件上获得此功能。如何访问此功能?

1 个答案:

答案 0 :(得分:0)

shallow无法呈现具有所有属性的完整组件集。方法。它适用于基本&#34;这件事是否符合我的预期?&#34;测试

mount会为您提供所有内容,并允许您测试所需内容。它对于测试事件处理非常有用。操纵组件的状态以测试组件之间的交互。

相关问题