components#useClickAway TypeScript Examples

The following examples show how to use components#useClickAway. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: click-away.test.tsx    From geist-ui with MIT License 5 votes vote down vote up
describe('UseClickAway', () => {
  it('should work correctly', () => {
    const handler = jest.fn()
    const ref = React.createRef() as React.MutableRefObject<HTMLDivElement>
    ref.current = document.createElement('div')
    const el = ref.current
    document.body.appendChild(el)
    renderHook(() => useClickAway(ref, handler))

    simulateNativeClick(el)
    expect(handler).not.toHaveBeenCalled()
    simulateNativeClick(document.body)
    expect(handler).toHaveBeenCalled()
  })

  it('should no errors when element missing', () => {
    const errorSpy = jest.spyOn(console, 'error')
    const ref = React.createRef<HTMLDivElement>()
    renderHook(() => useClickAway(ref, () => {}))

    expect(errorSpy).not.toHaveBeenCalled()
  })

  it('should update handler reference', async () => {
    const ref = React.createRef() as React.MutableRefObject<HTMLDivElement>
    ref.current = document.createElement('div')
    const handler1 = jest.fn()
    const handler2 = jest.fn()
    let isFirstRender = true
    const { rerender } = renderHook(() => {
      const handler = isFirstRender ? handler1 : handler2
      useClickAway(ref, handler)
      isFirstRender = false
    })
    simulateNativeClick(document.body)
    expect(handler1).toHaveBeenCalled()

    rerender()
    simulateNativeClick(document.body)
    expect(handler2).toHaveBeenCalled()
  })
})