Reactjs e、 target.parentNode.getAttribute(";id";)/e.target.getAttribute(";id";)单元测试jest enzyem

Reactjs e、 target.parentNode.getAttribute(";id";)/e.target.getAttribute(";id";)单元测试jest enzyem,reactjs,testing,events,jestjs,enzyme,Reactjs,Testing,Events,Jestjs,Enzyme,有人对event.target.getAttribute有jest/酶测试示例吗 handleButtonsClicks = () => { if(e.target.parentNode.getAttribute("id")=== "id1") { // } else if (e.target.getAttribute("id") === "id2") { // } } 谢谢这是一个完整的演示: i

有人对event.target.getAttribute有jest/酶测试示例吗

    handleButtonsClicks = () => {
      if(e.target.parentNode.getAttribute("id")=== "id1") {
        //
      } else if (e.target.getAttribute("id") === "id2") {
        //
      }
    }



谢谢

这是一个完整的演示:

index.tsx

import React,{Component}来自'React';
类SomeComponent扩展组件{
建造师(道具){
超级(道具);
this.handleButtonsClicks=this.handleButtonsClicks.bind(this);
}
把手按钮咔嗒声(e){
if(e.target.parentNode.getAttribute('id')='id1'){
log('do something');
}else if(e.target.getAttribute('id')=='id2'){
log('do other thing');
}
}
render(){
返回(
按钮1
按钮2
);
}
}
导出默认组件;
index.spec.tsx

从“React”导入React;
从“酶”导入{shall};
从“/”导入某些组件;
描述('SomeComponent',()=>{
让包装纸;
在每个之前(()=>{
包装器=浅();
开玩笑。恢复记忆();
});
测试('应处理按钮单击',()=>{
constlogspy=jest.spyOn(控制台,'log');
expect(wrapper.find('button')).toHaveLength(2);
const-mEvent={target:{parentNode:{getAttribute:jest.fn().mockReturnValueOnce('id1')}};
wrapper.find('#id1').simulate('click',mEvent);
expect(logSpy).toBeCalledWith('do something');
expect(mEvent.target.parentNode.getAttribute).toBeCalledWith('id');
});
测试('应处理按钮单击',()=>{
constlogspy=jest.spyOn(控制台,'log');
expect(wrapper.find('button')).toHaveLength(2);
常数mEvent={
目标:{
getAttribute:jest.fn().mockReturnValueOnce('id2'),
父节点:{getAttribute:jest.fn()}
}
};
wrapper.find('#id1').simulate('click',mEvent);
expect(logSpy).toBeCalledWith('do other thing');
expect(mEvent.target.getAttribute).toBeCalledWith('id');
});
});
单元测试结果:

通过src/stackoverflow/58457004/index.spec.tsx
某些成分
✓ 应处理按钮点击(16ms)
✓ 应处理按钮点击(3ms)
console.log node_modules/jest mock/build/index.js:860
做点什么
console.log node_modules/jest mock/build/index.js:860
做另一件事
-----------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
-----------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 83.33 | 100 | 100 ||
index.tsx | 100 | 83.33 | 100 | 100 | 12|
-----------|----------|----------|----------|----------|-------------------|
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:4.139s,估计8s

无论您尝试过什么,您遇到的问题是什么?你能分享一些你尝试过的东西吗?如果它不起作用呢?谢谢你的回答。我无法正确地模拟路径来模拟getAttribute的单击,并且没有根据不同的ID收到不同的结果。我现在看到了你的答案-非常感谢并标记为已解决
    <Button id="id1" onClick={handleButtonsClicks}/>
    <Button id="id2" onClick={handleButtonsClicks}/>