1 | import tap from 'tap'
|
2 |
|
3 | import { wrapHandler } from '../lib/wrapHandler'
|
4 | import { AWS } from '../lib/types'
|
5 |
|
6 | const context = {} as AWS['HandlerContext']
|
7 |
|
8 | function stubEvent(props: Partial<AWS['HandlerEvent']>): AWS['HandlerEvent'] {
|
9 | return {
|
10 | rawUrl: '',
|
11 | rawQuery: '',
|
12 | path: '',
|
13 | httpMethod: 'GET',
|
14 | headers: {},
|
15 | multiValueHeaders: {},
|
16 | queryStringParameters: null,
|
17 | multiValueQueryStringParameters: {},
|
18 | body: null,
|
19 | isBase64Encoded: false,
|
20 | ...props,
|
21 | }
|
22 | }
|
23 |
|
24 | tap.test('wrapHandler', async (t) => {
|
25 | t.plan(2)
|
26 |
|
27 | const handler = wrapHandler({
|
28 | route: '/:slug',
|
29 | async handler(event, context) {
|
30 | t.equal(event.routeParameters.slug, 'foo')
|
31 | return {
|
32 | body: 'foo',
|
33 | }
|
34 | },
|
35 | })
|
36 |
|
37 | const response = await handler(
|
38 | stubEvent({
|
39 | path: '/foo',
|
40 | }),
|
41 | context
|
42 | )
|
43 |
|
44 | t.equal(response.body, 'foo')
|
45 | })
|
46 |
|
47 | tap.test('wrapHandler - html fallback', async (t) => {
|
48 | const handler = wrapHandler({
|
49 | route: '/:slug',
|
50 | async handler(event, context) {
|
51 | throw Error()
|
52 | },
|
53 | })
|
54 |
|
55 | const response = await handler(
|
56 | stubEvent({
|
57 | path: '/foo',
|
58 | }),
|
59 | context
|
60 | )
|
61 |
|
62 | t.ok(response?.body?.includes('HTTP 500'))
|
63 | })
|
64 |
|
65 | tap.test('wrapHandler - json fallback', async (t) => {
|
66 | const handler = wrapHandler({
|
67 | route: '/:slug',
|
68 | async handler(event, context) {
|
69 | throw Error()
|
70 | },
|
71 | })
|
72 |
|
73 | const response = await handler(
|
74 | stubEvent({
|
75 | path: '/foo',
|
76 | headers: {
|
77 | Accept: 'application/json',
|
78 | },
|
79 | }),
|
80 | context
|
81 | )
|
82 |
|
83 | const body = JSON.parse(response.body || '')
|
84 |
|
85 | t.equal(body.errors.length, 1)
|
86 | })
|
87 |
|
88 | tap.test('wrapHandler - json fallback with details', async (t) => {
|
89 | const handler = wrapHandler({
|
90 | route: '/:slug',
|
91 | async handler(event, context) {
|
92 | const e = Error('message')
|
93 |
|
94 | e.title = 'test'
|
95 | throw e
|
96 | },
|
97 | })
|
98 |
|
99 | const response = await handler(
|
100 | stubEvent({
|
101 | path: '/foo',
|
102 | headers: {
|
103 | Accept: 'application/json',
|
104 | },
|
105 | }),
|
106 | context
|
107 | )
|
108 |
|
109 | const body = JSON.parse(response.body || '')
|
110 | const error = body.errors[0]
|
111 |
|
112 | t.equal(error.details, 'message')
|
113 | t.equal(error.title, 'test')
|
114 | })
|