Mocking refs in React function component

前端 未结 2 1475
情深已故
情深已故 2021-01-13 15:58

I have React function component that has a ref on one of its children. The ref is created via useRef.

I want to test the component with the shallow ren

2条回答
  •  隐瞒了意图╮
    2021-01-13 16:24

    The solution from slideshowp2 didn't work for me, so ended up using a different approach:

    Worked around it by

    1. Introduce a useRef optional prop and by default use react's one
    import React, { useRef as defaultUseRef } from 'react'
    const component = ({ useRef = defaultUseRef }) => {
      const ref = useRef(null)
      return 
    }
    
    1. in test mock useRef
    const mockUseRef = (obj: any) => () => Object.defineProperty({}, 'current', {
      get: () => obj,
      set: () => {}
    })
    
    // in your test
    ...
        const useRef = mockUseRef({ refFunction: jest.fn() })
        render(
          ,
        )
    ...
    

提交回复
热议问题