Hi,
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",
Hooks won't work properly until the next enzyme release, v3.10.
@ljharb Thank you for your information.
v3.10.0 has now been released.
@ljharb Thanks. But can you help me with my early question?
How to test handleOnChange,handleOthers,handleEffect with the current version?
They should all work in mount; but the facebook shallow renderer doesn't yet support useEffect, so that won't work in shallow.
the thing is now when I do instance.handleOthers = jest.fn();
It says TypeError: Cannot set property 'handleOthers' of null
Sure - functional components have no instance, and handleOthers here is a variable inside the function. It's never been, and never will be, possible to "stub" variables inside of a closure.
have you resolve this problem?
@lj383997002 I did not test callback function now.
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