如何测试在内部渲染子元素的组件?

时间:2019-05-26 13:25:34

标签: javascript reactjs jestjs enzyme

我有以下内容:

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

在父组件中,我在内部传递了这些道具和标签:

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

我不明白如何正确地对这些组件进行单元测试。例如,我想测试单击该组件时调用的onClick函数。

我写了这样的测试:

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

但是我有一个错误

  

预期模拟函数被调用了一次,但被调用了零次。

1 个答案:

答案 0 :(得分:4)

您错误地传递了道具。您不需要将子代作为命名属性传递。您可以在浅层方法中添加它。 onClick和className是道具,不应放在子项中。

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

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