Source:  Twitter logo

Just want to implement the unit test for my react component with using the Jest and Enzyme.

Is there a way to test the order? Let's say I have component Button, and I want to render icon and text at the same time.

And of course it's good to provide the alignment option to the user(Icon first or Children first).

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

How to test the iconAlign props with Jest and Enzyme?

Check on the type of the component

Check icon first

var button = TestUtils.renderIntoDocument(<Button />);

var buttonNode = ReactDOM.findDOMNode(button);
expect(buttonNode.props.children[0].type.name).toEqual("Icon")
4 users liked answer #0dislike answer #04
pshoukry profile pic
pshoukry

You could use a shallow render and compare the output. I am not familiar with the Jest syntax so that side of my example may be incorrect (I quickly referred to their website):

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

And then you could create another test for the "left" align.


The enzyme version of @pshoukry's answer.

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

For reference, here is the enzyme shallow rendering API documentation: https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md

3 users liked answer #1dislike answer #13
ctrlplusb profile pic
ctrlplusb

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).