如何在 React Jest 中测试 onClick 处理程序 +酶?
我知道这是重复的问题,但现有的答案似乎不起作用。 因此,我正在使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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 nameIn the future, just add
console.log(wrapper.debug())
or use debugger in IDE and check value ofwrapper.debug()
in IDE debugger's console. It prints component body as a JSX and really help with debugging in such cases.