<%- tplTsOnly(['/// <reference types="mocha"/>', '']) %>
<%- tplImports('assert', null, 'req') %>
<%- tplImports('rp', 'request-promise', 'req') %>
<%- tplTsOnly(`import { Server } from 'http'${sc}\n`) -%>
<%- tplImports('url', null, 'req') %>
<%- tplImports('app', `../${specs.app.src}/app`) %>

const port = app.get('port') || 3030<%- sc %>
const getUrl = <%- tplJsOrTs('pathname', '(pathname?: string)') %> => url.format({
  hostname: app.get('host') || 'localhost',
  protocol: 'http',
  port,
  pathname
})<%- sc %>

describe('Feathers application tests', () => {
  let server<%- tplTsOnly(': Server') -%><%- sc %>

  before(function (done) {
    server = app.listen(port)<%- sc %>
    server.once('listening', () => {
      setTimeout(() => done(), 500)<%- sc %>
    })<%- sc %>
  })<%- sc %>

  after(function (done) {
    server.close()<%- sc %>
    setTimeout(() => done(), 500)<%- sc %>
  })<%- sc %>

  it('starts and shows the index page', () => {
    return rp(getUrl()).then(<%- tplJsOrTs('body', '(body: string)') %> =>
      assert.ok(body.indexOf('<html>') !== -1, 'response does not contain <html>')
    )<%- sc %>
  })<%- sc %>

  describe('404', function () {
    it('shows a 404 HTML page', () => {
      return rp({
        url: getUrl('path/to/nowhere'),
        headers: {
          Accept: 'text/html'
        }
      }).catch(res => {
        assert.strictEqual(res.statusCode, 404, 'unexpected statusCode')<%- sc %>
        assert.ok(res.error.indexOf('<html>') !== -1, 'error does not contain <html>')<%- sc %>
      })<%- sc %>
    })<%- sc %>

    it('shows a 404 JSON error without stack trace', () => {
      return rp({
        url: getUrl('path/to/nowhere'),
        json: true
      }).catch(res => {
        assert.strictEqual(res.statusCode, 404, 'unexpected statusCode')<%- sc %>
        assert.strictEqual(res.error.code, 404, 'unexpected error.code')<%- sc %>
        assert.strictEqual(res.error.message, 'Page not found', 'unexpected error.message')<%- sc %>
        assert.strictEqual(res.error.name, 'NotFound', 'unexpected error.name')<%- sc %>
      })<%- sc %>
    })<%- sc %>
  })<%- sc %>
})<%- sc %>
