【问题标题】:simulate child component element click in parent component test file在父组件测试文件中模拟子组件元素点击
【发布时间】:2020-03-05 14:17:36
【问题描述】:

我找不到模拟父测试文件的子组件中存在的元素单击的方法。

let card;

const displayCardSection = (cardName) => {
  card = cardName;
};

describe('Parent component', () => {
  it('simulate click event on child link', () => {
    const component = mount(<Parent
    />);
    const res = component.find(<Child
        onLinkClick={displayCardSection(CM_CARD)}
    />);
    expect(res).toBeDefined();
    res.exists('#cm_link').simulate('click');
    expect(card).toBe(CM_CARD);
  })
})

这是一个父组件的测试文件。

Parent.jsx:

class Parent extends Component {

  handleClick = () => {
    console.log('link clicked!');
  };

  render() {

    const linkText = 'Link'
    return (
      <Child 
        linkText={linkText}
        onLinkClick={handleClick}
      />
    );
  }
}

Child.jsx:

function Child({linkText, onLinkClick}) {
  return (
    <Link id="cm_link" onClick={onLinkClick}>{linkText}</Link>
    );
}

这些是我拥有的组件。

我希望模拟来自父组件的子组件的链接点击,输出应该是显示的卡片是“CM_CARD”。我可以写一个断言语句,但我不会模拟一个元素的点击事件,该元素存在于子元素中,但事件在父元素本身中处理。

【问题讨论】:

  • 模拟点击线使用.exists。在 Enzyme 的文档中,他们说:.exists([selector]) =&gt; Boolean

标签: javascript reactjs jestjs enzyme react-testing-library


【解决方案1】:

首先我建议使用shallow,代码如下:

const component = shallow(<Parent />);

// The following code should trigger the handler and then you will see the console output 
component.find("Child").prop("onLinkClick")();

我希望这是有用的,并能解决你的问题,祝你有美好的一天!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-30
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 2012-12-07
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多