import { expect } from 'chai'; import { Middleware } from '../../src/middleware'; import { MockEndpoint } from '../support/mockendpoint'; import { getMockAPIEvent } from '../support/mockapievent'; import { Endpoint, Request, Response } from '../../src/http'; import { HTTPError, MethodNotAllowed, InternalError, BadRequest } from '../../src/http/errors'; describe('A base Endpoint object', () => { let event = getMockAPIEvent(); let endpoint = new Endpoint(); let handler: any; let verbs = [ 'GET', 'PUT', 'POST', 'DELETE' ]; it('should return a function from handler()', () => { handler = endpoint.handler(); expect(typeof handler).to.equal('function'); }); it('should register Middleware', () => { endpoint.register(new Middleware()); expect(endpoint.middleware.length).to.equal(1); expect(endpoint.before.length).to.equal(1); expect(endpoint.after.length).to.equal(1); }); it('should have get, put, post, and delete methods', () => { expect(endpoint.get).to.exist; expect(endpoint.put).to.exist; expect(endpoint.post).to.exist; expect(endpoint.delete).to.exist; }); for (let verb of verbs) { it(`should return an error when ${verb}() is not implemented`, async () => { event.httpMethod = verb; let res = await handler(event); expect(res.statusCode).to.equal(405); }); } }); describe('An Endpoint', () => { let event = getMockAPIEvent(); let endpoint = new MockEndpoint(); let handler = endpoint.handler(); it('should handle an APIGatewayEvent', async () => { event.httpMethod = 'GET'; let res = await handler(event, {}); expect(res.headers).to.exist; expect(res.statusCode).to.equal(200); expect(res.body).to.exist; }); it('should return a MethodNotAllowed error when not implemented', async () => { event.httpMethod = 'PUT'; let res = await handler(event, {}); expect(res.headers).to.exist; expect(res.statusCode).to.equal(405); expect(res.body).to.exist; }); it('should handle the return of an HTTPError', async () => { event.httpMethod = 'GET'; event.body = JSON.stringify({ bad_request: true }) let res = await handler(event, {}); expect(res.headers).to.exist; expect(res.statusCode).to.equal(400); expect(res.body).to.exist; }); it('should turn generic Error object into InternalError objects', async () => { event.headers['Content-Type'] = 'application/json'; event.body = JSON.stringify({ exception: true }); let res = await handler(event, {}); expect(res.headers).to.exist; expect(res.statusCode).to.equal(500); expect(res.body).to.exist; }); });