【问题标题】:What is the best way to test methods that traverse the react components测试遍历反应组件的方法的最佳方法是什么
【发布时间】:2015-12-31 03:25:05
【问题描述】:

我尝试测试小型反应组件。以下组件是一个选项卡系统,当单击选项卡时,更改被单击选项卡的类名。它正在工作,但我想测试它们,但我不知道测试遍历许多组件的方法的步骤是什么。我把代码放在上面了。

TabSystem:有一个改变当前Tab状态的方法,这个方法是作为渲染每个标签的标签组件中的prop。

React.createClass({
  ....
  handleClick (currentTab) {
    this.setState({ currentTab })
  },

  render () {
    return (
      <div>
        <Tabs tabs = {tabs2} currentTab = {this.state.currentTab} onClick = {this.handleClick}/>
      </div>
    )
  }
});

Tabs: 接收到onClick prop 的父方法,这个方法作为prop 到tab 组件中,我的目标是只在tab 的名称中添加onClick 方法。

React.createClass({
  ...
  renderTabs () {
    return this.props.tabs.map((tab, index) => {
      var classname = index === this.props.currentTab ? 'active' : null;
      var clickHandler = this.props.onClick.bind(null, index);
      return (
        <Tab key={tab.name} onClick={clickHandler} index={index} className={classname} name={tab.name}/>
      )
    })
  },
  render () {
    return (
      <div>
        {this.renderTabs()}
      </div>
    )
  }
});

Tab:再次接收到 onClick 属性的父方法。

React.createClass({
  render () {
    return (
      <span className={this.props.className} onClick={this.props.onClick}>
        {this.props.name}
      </span>
    )
  }
});

测试此方法的最佳方法是什么?我是否需要在所有组件中都使用行之有效的方法?

【问题讨论】:

    标签: reactjs testing jestjs


    【解决方案1】:

    我编写了一个测试库,抽象了 React 的测试工具。 https://github.com/Legitcode/tests 你可以这样做:

    Test(<TestComponent />)
    .find('button')
    .simulate({method: 'click', element: 'button'})
    .element(button => {
      expect(button.props.className).to.be.equal('blah');
    })
    

    您明白了,希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-16
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多