首页 文章

酶无法使用mount找到要点击的元素

提问于
浏览
0

我有一个选项卡React组件,我正在使用Enzyme和Jest进行测试 .

这是组件:

class TabbedArea extends React.Component{


  constructor(props) {
    super(props)

    this.handleClick = this.handleClick.bind(this);
    this.state = {
      activeIndex: this.props.activeIndex || 0
    };
  }

  componentWillReceiveProps(nextProps){
    if (this.state.activeIndex !== nextProps.activeIndex) {
      this.setState({
        activeIndex: nextProps.activeIndex
      });
    }
  }

  handleClick(index, e) {
    e.preventDefault();
    this.setState({
      activeIndex: index
    });
  }

  tabNodes() {
    return (_.map(this.props.children, (child, index) => {
        let className = classNames({'active': this.state.activeIndex === index});
          return (
            <li key={index} onClick={(e) => this.handleClick(index, e)}>
              <a className={className} href="#">{child.props.display}</a>
            </li>
          )
        }
      )
    )
  }

  contentNodes() {
    return (
      _.map(this.props.children, (child, index) => {
        if(this.state.activeIndex === index) {
          return (
            <div className="TabPane" key={index}>
              {child.props.children}
            </div>
          )
        }
      }
      )
    )
  }

  render() {

    return (
      <div className={`${styles.ParcelResultsTrackingHistory} col-md-12`}>
        <ul className="nav nav-tabs" id="navTabs">
          {this.tabNodes()}
        </ul>
        <section>
          {this.contentNodes()}
        </section>
      </div>
    );
  }

}

export default TabbedArea;

这是我的测试:

describe('Given the Tabbed Area component is rendered', () => {


  describe('Initial Snapshots', () => {
    let component
    beforeEach(() => {
      component = shallow(<TabbedArea />)
    })
    it('should be as expected', () => {
      expect(shallowToJson(component)).toMatchSnapshot()
    })
  })

  describe('I click on the second tab', () => {
    let component
    let tab2

    component = shallow(<TabbedArea/>)
    tab2 = component.find('ul li').at(1);
    tab2.simulate('click');

    describe('the content of the second tab is rendered', () => {
      component.update();

      it('should match the snapshot', () => {
        expect(shallowToJson(component)).toMatchSnapshot()
      });

    });

  });

  describe('Clicking on the tab', () => {
    const wrapper = mount(<TabbedArea/>)
    const handleClick = jest.spyOn(wrapper.instance(), 'handleClick');
    wrapper.update();
    const tab = wrapper.find('ul#navTabs li').first()
    tab.simulate('click')

    it('will call handleClick', () => {
      expect(handleClick).toBeCalled();
    });
  });

})

快照测试运行正常,但是当我尝试测试 handleClick 时它失败了: Method “simulate” is only meant to be run on a single node. 0 found instead. 任何想法为什么't find the node? I'试图通过id找到 li 但是得到了同样的错误 .

谢谢

1 回答

  • 0

    不是因为你在没有孩子的情况下渲染 <TabbedArea> . tabNodes 方法循环 this.props.children ,在您的测试中为空 .

相关问题