UNPKG

2.24 kBJavaScriptView Raw
1import { handler } from '../src/index';
2import { LogEnv } from '@erikmuir/lambda-utils';
3import { authorize } from '../src/services/AuthorizerFacade';
4import UnauthorizedException from '../src/exceptions/UnauthorizedException';
5
6jest.mock('@erikmuir/lambda-utils/dist/utilities/LambdaLogger');
7jest.mock('../src/services/AuthorizerFacade');
8
9describe('index', () => {
10 describe('handler', () => {
11 beforeEach(() => {
12 jest.clearAllMocks();
13 });
14
15 afterAll(() => {
16 jest.restoreAllMocks();
17 });
18
19 test('sets event on environment wrapper', async () => {
20 const event = { foo: 'bar' };
21
22 await handler(event, {});
23
24 expect(LogEnv.lambdaEvent).toBe(event);
25 });
26
27 test('sets context on environment wrapper', async () => {
28 const context = { foo: 'bar' };
29
30 await handler({}, context);
31
32 expect(LogEnv.lambdaContext).toBe(context);
33 });
34
35 test('calls authorize', async () => {
36 const event = {};
37
38 await handler(event, {});
39
40 expect(authorize).toHaveBeenCalledTimes(1);
41 expect(authorize).toHaveBeenCalledWith(event);
42 });
43
44 test('when unauthorized exception is thrown, then rethrows', async () => {
45 const exception = new UnauthorizedException();
46 authorize.mockImplementation(() => {
47 throw exception;
48 });
49
50 try {
51 await handler();
52
53 expect(true).toBe(false); // should never happen
54 } catch (e) {
55 expect(e).toBe(exception);
56 }
57 });
58
59 test('when a non-unauthorized exception is thrown, then throws new unauthorized exception', async () => {
60 const exception = new Error();
61 authorize.mockImplementation(() => {
62 throw exception;
63 });
64
65 try {
66 await handler();
67
68 expect(true).toBe(false); // should never happen
69 } catch (e) {
70 expect(e).not.toBe(exception);
71 expect(e instanceof UnauthorizedException).toBe(true);
72 }
73 });
74
75 test('returns response', async () => {
76 const response = {};
77 authorize.mockReturnValue(response);
78
79 const actual = await handler();
80
81 expect(actual).toBe(response);
82 });
83 });
84});