import React from 'react'
import ErrorAlert from 'components/ErrorAlert'
import { shallow } from 'enzyme'
import ConsoleWatcher from '../utils/ConsoleWatcher'

describe('(Component) ErrorAlert', function () {
  let _console

  const defaultProps = {
    header: 'This is my header string!',
    message: 'This is my message string!'
  }

  before(function () {
    _console = new ConsoleWatcher()
  })

  beforeEach(function () {
    _console.watchForErrors()
  })

  afterEach(function () {
    _console.restore()
  })

  /**
   * Provided some props, this will attempt to render the componenet with said props
   */
  function assertRendersWithProps (props) {
    let wrapper = shallow(<ErrorAlert {...props} />)
    expect(wrapper.html()).to.not.equal(null)

    if (props.header !== undefined) {
      const header = wrapper.find('h4')
      expect(header).to.exist
      expect(header.text()).to.match(new RegExp(defaultProps.header))
    }

    // Look for our paragraph elements.  There may be multiple if props.error was also set.
    let paragraphs = wrapper.find('p')

    if (props.error !== undefined) {
      expect(paragraphs).to.have.length(2)  // error will always be 2nd paragraph.
      const error = paragraphs.at(1)
      expect(error.text()).to.match(new RegExp(defaultProps.error))
    } else {
      // Should only be 1 paragraph element if props.error wasn't set.
      expect(paragraphs).to.have.length(1)
    }

    if (props.message) {
      const message = paragraphs.at(0)  // message will always be 1st paragraph.
      expect(message).to.exist
      expect(message.text()).to.match(new RegExp(defaultProps.message))
    }
  }

  function assertThrowsErrorWithProps (props) {
    var fn = function () {
      return shallow(<ErrorAlert {...props} />)
    }
    expect(fn).to.throw(Error)
  }

  it('should render', function () {
    assertRendersWithProps(defaultProps)
  })

  it('should render with error prop', function () {
    let props = defaultProps
    props.error = 'This is my error string!'
    assertRendersWithProps(props)
  })

  it('should throw error if missing required props', function () {
    assertThrowsErrorWithProps({})
    assertThrowsErrorWithProps({ header: defaultProps.header })   // Missing header prop
  })
})
