[英]How to test functions inside functional components with React hooks?
I have a functional component which uses useState hook as shown below:我有一个使用 useState 钩子的功能组件,如下所示:
import React,{useState} from 'react';
export const PList = (props) =>{
const [obj, setObj]= useState({
value: null,
open: null
});
let onDeleteList = (data) =>{
setObj({....});
};
return(
<React.Fragment>
{
props.arr.map((p,i)=>{
return <childA onDeleteList={onDeleteList} />
})
}
</React.Fragment>
);
}
I an using Jest+ enzyme and looking to write a test case to test the onDeleteList function in this component.我使用 Jest+ 酶并希望编写一个测试用例来测试此组件中的 onDeleteList function。 I have tried with the below code:
我已经尝试使用以下代码:
describe('PList',()=>{
let wrapper = shallow(<Plist {...props}/>);
it('should call onDeleteList',()=>{
expect(wrapper.find('onDeleteList')).toBeTruthy();
});
});
I am not sure if this is the correct way, the coverage report still shows the onDeleteList() is not covered in the test case.我不确定这是否是正确的方法,覆盖率报告仍然显示 onDeleteList() 未包含在测试用例中。 Can anyone please advise how can I write a test case for this scenario?
谁能告诉我如何为这种情况编写测试用例?
This is how you should be testing:这就是你应该如何测试:
import childA here
describe('PList',()=>{
let wrapper = shallow(<Plist {...props}/>);
it('should call onDeleteList',()=>{
const onDeleteListHandler=wrapper.find(childA).at(0).prop("onDeleteList");
onDeleteListhandler(pass your data here);
expect(onDeleteListhandler).toHaveBeenCalledTimes(1);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.