Enzyme: Question: How to test useCallback in a functional component?

Created on 28 May 2019  路  10Comments  路  Source: enzymejs/enzyme

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",

All 10 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aweary picture aweary  路  3Comments

heikkimu picture heikkimu  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments

benadamstyles picture benadamstyles  路  3Comments

nelsonchen90 picture nelsonchen90  路  3Comments