Question: How to test useCallback in a functional component?
See original GitHub issueHi,
Previously using class
component method, I do the following:
describe('dummy text', () => {
it('[onChange]: Should call handleOthers', () => {
const wrapper = mount(<Component/>)
const instance = wrapper.instance();
instance.handleOthers = jest.fn();
instance.onChange();
expect(instance.handleOthers).toHaveBeenCalled();
})
Now I am trying the hook way(react v16.8.6), which the test above obviously breaks at instance
.
const Component = memo(({a, b} => {
const el = useRef(null)
const [val, setVal] = useState('')
const handleOnChange = useCallback((e)=>{
setVal(el.current.value)
}, [])
const handleOthers = useCallback(()=>{}, [])
const handleEffect = useCallback(()=>{}, [])
useEffect(()=>{
handleEffect()
},[])
return (
<div><input ref={el} onChange={handleOnChange} /></div>
)
}))
How to test handleOnChange
,handleOthers
,handleEffect
respectively?
"react": "^16.8.6",
"react-dom": "^16.8.6"
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.13.2",
"jest": "^23.6.0",
Issue Analytics
- State:
- Created 4 years ago
- Reactions:3
- Comments:11 (4 by maintainers)
Top Results From Across the Web
How to Test React Hooks useEffect, useCallBack
React functional components don't expose component instance and supposed to be tested by asserting the result. Tests can be strengthened up ...
Read more >Testing React Hooks - Tosh - Medium
To test useCallback I created a small component with only one button. It has a function that console.log “You clicked” and the buttonName...
Read more >Your Guide to React.useCallback() - Dmitri Pavlutin
React.useCallback() memoizes callback functions. ... A functional component wrapped inside React.memo() accepts a function object prop ...
Read more >Learn How to Tame React's useCallback Hook - Kinsta
Wondering how React handles memoization? Level up your React skills by learning how to harness the useCallback hook to prevent re-rendering.
Read more >How to test React Hooks - LogRocket Blog
The other Hook that's in use here is the useEffect Hook. The useEffect Hook adds the ability to perform side effects from a...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Hey, I am trying to test
useCallback
as mentioned above but I don’t want to test it by creating a custom hook and installing the library is there any other way to test it normally @edwardfxiao ?You can put
useCallback
functions in another hook and later use this library to test your code: https://github.com/testing-library/react-hooks-testing-library