import {
  handleError
} from '../helpers'
import { TRAY_ALERT_OPEN, SET_UI, ADD_ALERT } from '@instructure/quiz-common/lib/constants'

describe('api helpers', () => {
  const dispatchStub = sinon.stub()

  afterEach(() => {
    dispatchStub.resetHistory()
  })

  it('opens the tray alert if 404 or 401 error', (done) => {
    handleError(dispatchStub)({ response: { status: 404 } })
    setTimeout(() => {
      expect(dispatchStub).to.have.been.calledWith({
        payload: { key: TRAY_ALERT_OPEN, value: true },
        type: SET_UI
      })
      done()
    }, 500)
  })

  it('dispatches a generic error if not 404 or 401', () => {
    handleError(dispatchStub)({ response: { status: 500 } })
    expect(dispatchStub).to.have.been.calledOnce()
    expect(dispatchStub).to.have.been.calledWithMatch({
      type: ADD_ALERT,
      payload: {
        message: 'Sorry, there was a 500 Error.',
        variant: 'error'
      }
    })
  })

  it('uses custom error message if given', () => {
    const errorMessage = 'O NOES'
    handleError(dispatchStub, errorMessage)({ response: { status: 500 } })
    expect(dispatchStub).to.have.been.calledOnce()
    expect(dispatchStub).to.have.been.calledWithMatch({
      type: ADD_ALERT,
      payload: {
        message: errorMessage,
        variant: 'error'
      }
    })
  })
})
