【问题标题】:How to access child of a component in jest in a react/redux app如何在 react/redux 应用程序中开玩笑地访问组件的子组件
【发布时间】:2017-12-08 14:53:05
【问题描述】:

我喜欢在 Redux 应用程序中测试 Connect 内的组件:

this.component = TestUtils.renderIntoDocument(<Provider store={store}><Header path={this.path} /></Provider>);

我不知道如何在 Provider 中访问 Header...(因为从 CLI 运行笑话时,我无法在调试器中停下来。

所以当我试图让一个孩子进入 Header 时

      const path = findDOMNode(self.component.refs.pathElemSpan);
      console.log("path="+path)

路径未定义

有什么建议吗?

谢谢

【问题讨论】:

    标签: reactjs redux jestjs


    【解决方案1】:

    你在找这个吗?

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    
    function App() {
      return (
        <div>
          <Welcome name="Sara" />
          <Welcome name="Cahal" />
          <Welcome name="Edite" />
        </div>
      );
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById('root')
    );
    

    【讨论】:

      【解决方案2】:

      使用enzyme,你有一堆不错的选择器可以在你的虚拟 DOM 王国中导航。 :)

      http://airbnb.io/enzyme/

      访问组件的超级简单测试:

      import { mount } from 'enzyme'
      import Header from './header'
      
      //... in your test
      const wrapper = mount(<Provider store={store}><Header path='foo' /></Provider>)
      const header = wrapper.find(Header).first()
      expect(header.exists()).toBe(true)
      // you can even check out the props
      expect(header.prop('path')).toBe('foo')
      

      此示例使用mount,但您也可以选择进行浅层渲染。我强烈建议您喝点东西并阅读一下文档。 ;)

      【讨论】:

        【解决方案3】:
        import Foo from '../components/Foo';
        
        
        const wrapper = mount(<MyComponent />);
        
        expect(wrapper.find(Foo)).to.have.lengthOf(1); //you can use this one
        expect(wrapper.find('Foo')).to.have.lengthOf(1); //you can use this one as well
        

        【讨论】:

        • 这个答案似乎是使用 Enzyme 的包装器,它是随 jest 自动安装的。确保您记下您的答案所需的任何额外依赖项。如果您建议提问者使用 Enzyme,请说明原因。
        猜你喜欢
        • 1970-01-01
        • 2021-08-01
        • 1970-01-01
        • 2019-11-22
        • 1970-01-01
        • 2021-01-09
        • 2019-08-01
        • 2017-07-13
        • 2019-11-19
        相关资源
        最近更新 更多