Ad

How To Test Component Which Render Children Elements Inside?

- 1 answer

I have following component:

export default function Button({ className, children, ...otherProps }) {
  return (
    <button className={'button} {...otherProps}>
      {children}
    </button>
  );
}

and in parent component I passed such props and tag inside:

<Button className={test-button} onClick={this.removeItems} >
    <i className="fa fa-trash-alt" /> Remove all items
</Button>

I cannot understand how to properly unit test such components. For example I want to test onClick function to have been called when I click on the component.

I wrote such a test:

const buttonFunc = jest.fn();
    const props = {
        children: {
        className: "test",
        onClick: buttonFunc,
    }
};

let wrapper;

beforeEach(() => {
    wrapper = shallow(<Button {...props} />);
});

test('click on switch button', () => {
    wrapper.simulate('click');
    expect(buttonFunc).toHaveBeenCalledTimes(1);
    console.log(wrapper.debug())
});

but I have an error

Expected mock function to have been called one time, but it was called zero times.

Ad

Answer

You are passing props wrongly. You don't need to pass children as named property. you can add that in your shallow method. onClick and className are props, should not be inside children.

const props = {
    className: "test",
    onClick: buttonFunc,
};

wrapper = shallow(<Button {...props}> Button Text </Button>);
Ad
source: stackoverflow.com
Ad