import { mount } from 'enzyme'
import React from 'react'
import { assignRef, mergeRefs } from '../mergeRefs'

const refValue = 'ref'

describe('assignRef', () => {
  it('should call callback ref with value', () => {
    const refAsFunc = jest.fn()
    assignRef(refAsFunc, refValue)

    expect(refAsFunc).toHaveBeenCalledTimes(1)
    expect(refAsFunc).toHaveBeenCalledWith(refValue)
  })

  it('should assign value to ref object', () => {
    const refAsObj = { current: undefined }
    assignRef(refAsObj, refValue)

    expect(refAsObj.current).toBe(refValue)
  })

  it('should ignore when ref equals null', () => {
    const refAsObj = null
    assignRef(refAsObj, refValue)

    expect(refAsObj).toBe(null)
  })
})

test('mergeRefs', () => {
  const Dummy = React.forwardRef((_, forwardRef) => {
    React.useImperativeHandle(forwardRef, () => refValue)
    return null
  })

  const refAsFunc = jest.fn()
  const refAsObj = { current: undefined }

  const Example = ({ visible }) => {
    if (visible) {
      return <Dummy ref={mergeRefs(refAsFunc, refAsObj)} />
    }
    return null
  }

  const wrapper = mount(<Example visible />)

  expect(refAsFunc).toHaveBeenCalledTimes(1)
  expect(refAsFunc).toHaveBeenCalledWith(refValue)
  expect(refAsObj.current).toBe(refValue)

  wrapper.setProps({ visible: false })

  expect(refAsFunc).toHaveBeenCalledTimes(2)
  expect(refAsFunc).toHaveBeenCalledWith(null)
  expect(refAsObj.current).toBe(null)
})
