import { mount } from 'enzyme'
import React from 'react'
import {
  Component,
  getProps,
  testContext,
  testHook,
  testRenderProp,
} from '../../__tests__/helpers/state'
import { Timer, TimerProvider, useTimer, useTimerContext } from '../Timer'

const validateAPI = (api) => {
  expect(api.setTimer).toBeInstanceOf(Function)
}

const apiTest = {
  test: 'api',
  config: {},
  callback: validateAPI,
}

describe('Timer', () => {
  it('calls the provided function after the given time', (done) => {
    const Enhanced = () => <Component {...useTimer()} />
    const dom = mount(<Enhanced />)
    const props = getProps(Component, dom)()
    const spy = jest.fn()
    props.setTimer(spy, 1000)
    expect(spy).toBeCalledTimes(0)
    setTimeout(() => {
      expect(spy).toBeCalledTimes(1)
      done()
    }, 1500)
  })

  testHook(useTimer, [apiTest])

  testRenderProp(Timer, 'timer', [apiTest])

  testContext(TimerProvider, useTimerContext, [
    apiTest,
    {
      test: 'missing provider',
      config: {},
      injectProvider: false,
      callback: (context, { spy }) => {
        spy.mockImplementation(() => {})

        expect(context.timerId).toBe(null)
        context.setTimer()
        expect(spy).toBeCalledTimes(1)
        expect(spy).toBeCalledWith(
          'Could not call `setTimer`, please wrap your component in a `<TimerProvider>`'
        )

        spy.mockRestore()
      },
    },
  ])
})
