如何在 React Jest 中测试 onClick 处理程序 +酶?

发布于 2025-01-11 20:10:45 字数 679 浏览 3 评论 0原文

我知道这是重复的问题,但现有的答案似乎不起作用。 因此,我正在使用 SemanticUI 中的样式,并尝试在其 HTML 元素之一上测试 onClick 处理程序

处理程序代码:

        <div className="title active" onClick={(): void => handleClick(idx)}>
          <i className="dropdown icon"></i>
          {item.title}
        </div>

测试此组件:

  const component = <Accordion items={items} />
  it('should find onClick element', () => {
    const wrapper = mount(component)
    wrapper.find('.title-active').simulate('onClick')
  })
})

失败并出现错误:方法“simulate”应在 1 个节点上运行。相反,找到了 0。

在这个问题上搜索更多信息,我发现我没有正确选择 css 选择器,就我而言,我认为是正确的。 如何解决这个问题?

I know this is repeated question but the existing answers don't seem to work.
So I am using styles from SemanticUI and trying to test onClick handler on one of its HTML elements

Code for Handler :

        <div className="title active" onClick={(): void => handleClick(idx)}>
          <i className="dropdown icon"></i>
          {item.title}
        </div>

Testing for this component :

  const component = <Accordion items={items} />
  it('should find onClick element', () => {
    const wrapper = mount(component)
    wrapper.find('.title-active').simulate('onClick')
  })
})

It fails with error : Method “simulate” is meant to be run on 1 node. 0 found instead.

Searching more on this issue I found out I'm not selecting the css selector correctly, which in my case I think am.
How to fix this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

年华零落成诗 2025-01-18 20:10:45

className="title active".title-active 永远不会匹配。选择器应该是 .title.active ,或者您在类名中漏掉了破折号

。将来,只需添加 console.log(wrapper.debug()) 或在 IDE 中使用调试器并在 IDE 调试器的控制台中检查 wrapper.debug() 的值。它将组件主体打印为 JSX,并且在这种情况下确实有助于调试。

className="title active" and .title-active will never match. Either selector should be .title.active or you missed dash in class name

In the future, just add console.log(wrapper.debug()) or use debugger in IDE and check value of wrapper.debug() in IDE debugger's console. It prints component body as a JSX and really help with debugging in such cases.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文