【问题标题】:Way to test the order of elements in React在 React 中测试元素顺序的方法
【发布时间】:2016-06-01 06:12:10
【问题描述】:

只想使用JestEnzyme 为我的react 组件实现单元测试。

有没有办法测试订单?假设我有组件 Button,我想同时渲染图标和文本。

当然最好为用户提供对齐选项(图标优先或儿童优先)。

Button.js

class Button extends React.Component {
    constructor() {
        super();
    }
    render() {
        let content;
        const icon = (<Icon type='search' />);
        if (this.props.iconAlign === 'right') {
            content = (<span>{this.props.children} {icon}</span>
        } else {
            content = (<span>{icon} {this.props.children}</span>
        }
        return (
            <button>{content}</button>
        );
    }
}

如何使用 JestEnzyme 测试 iconAlign 道具?

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    检查组件的类型

    先检查图标

    var button = TestUtils.renderIntoDocument(<Button />);
    
    var buttonNode = ReactDOM.findDOMNode(button);
    expect(buttonNode.props.children[0].type.name).toEqual("Icon")
    

    【讨论】:

      【解决方案2】:

      您可以使用浅层渲染并比较输出。我不熟悉 Jest 语法,因此我的示例可能不正确(我很快参考了他们的网站):

      import { shallow } from 'enzyme';
      
      describe(`Button`, () => {
        it(`should render the icon on the right`, () => {
          const children = <div>foo</div>;
          const actual = shallow(
            <Button iconAlign="right" children={children} />
          );
          const expected = (
            <button><span>{children} <Icon type='search' /></span></button>
          );
          expect(actual.matchesElement(expected)).toBeTruthy();
        });
      });
      

      然后您可以为“左”对齐创建另一个测试。


      @pshoukry 答案的酶版本。

      describe(`Button`, () => {
        it(`should render icon on the right`, () => {
          const wrapper = shallow(
            <Button iconAlign="right">
              <div>foo</div>
            </Button>
          );
          const iconIsOnRight = wrapper.find('span').childAt(1).is(Icon);
          expect(iconIsOnRight).toBeTruthy();
        });
      });
      

      供参考,这里是酶浅渲染API文档:https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        • 2022-01-11
        相关资源
        最近更新 更多