Skip to content

Commit 58d7423

Browse files
committed
update tests to match new testRequest logic
1 parent dbe759c commit 58d7423

10 files changed

+148
-140
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.
44

55
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html)
66

7+
## [4.4.2]  (2020-11-25)
8+
9+
### Fixed
10+
11+
- Update calculation of `testRequest` prop on api signature based on headers
12+
713
## [4.4.1]  (2020-11-25)
814

915
### Changed
@@ -342,6 +348,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/),
342348
- Update older libraries
343349
- Now publish from Git tags instead of master pushes
344350

351+
[4.4.2]: https://github.com/manwaring/lambda-wrapper/compare/v4.4.1...v4.4.2
345352
[4.4.1]: https://github.com/manwaring/lambda-wrapper/compare/v4.4.0...v4.4.1
346353
[4.4.0]: https://github.com/manwaring/lambda-wrapper/compare/v4.3.0...v4.4.0
347354
[4.3.0]: https://github.com/manwaring/lambda-wrapper/compare/v4.2.0...v4.3.0

package-lock.json

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@manwaring/lambda-wrapper",
33
"description": "A lambda handler wrapper to abstract common functionality and provide useful defaults",
4-
"version": "4.4.1",
4+
"version": "4.4.2",
55
"scripts": {
66
"publish-please-dry-run": "publish-please --dry-run",
77
"publish-please": "publish-please",
@@ -23,7 +23,7 @@
2323
"@types/aws-lambda": "^8.10.64",
2424
"@types/cfn-response": "^1.0.4",
2525
"@types/jest": "^26.0.15",
26-
"@types/node": "^14.14.9",
26+
"@types/node": "^14.14.10",
2727
"@typescript-eslint/eslint-plugin": "^4.8.2",
2828
"@typescript-eslint/parser": "^4.8.2",
2929
"aws-lambda": "^1.0.6",

src/api/v1/parser.test.ts

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,72 @@
1-
import { stringify } from 'querystring';
2-
import { apiGatewayEvent } from 'serverless-plugin-test-helper';
3-
import { Request, Body } from './parser';
1+
import { stringify } from "querystring";
2+
import { apiGatewayEvent } from "serverless-plugin-test-helper";
3+
import { Request, Body } from "./parser";
44

5-
describe('Body parsing', () => {
6-
it('Parses json body', () => {
7-
const json = { hello: 'world' };
8-
const headers = { 'content-type': 'application/json' };
5+
describe("Body parsing", () => {
6+
it("Parses json body", () => {
7+
const json = { hello: "world" };
8+
const headers = { "content-type": "application/json" };
99
const body = new Body(JSON.stringify(json), headers).getParsedBody();
1010
expect(body).toEqual(json);
1111
});
1212

13-
it('Parses json body when charset is also defined in the content-type', () => {
14-
const json = { hello: 'world' };
15-
const headers = { 'content-type': 'application/json;charset=UTF-8' };
13+
it("Parses json body when charset is also defined in the content-type", () => {
14+
const json = { hello: "world" };
15+
const headers = { "content-type": "application/json;charset=UTF-8" };
1616
const body = new Body(JSON.stringify(json), headers).getParsedBody();
1717
expect(body).toEqual(json);
1818
});
1919

20-
it('Parses form url encoded body', () => {
21-
const form = { hello: 'world' };
22-
const headers = { 'content-type': 'application/x-www-form-urlencoded' };
20+
it("Parses form url encoded body", () => {
21+
const form = { hello: "world" };
22+
const headers = { "content-type": "application/x-www-form-urlencoded" };
2323
const body = new Body(stringify(form), headers).getParsedBody();
2424
expect(body).toEqual(form);
2525
});
2626

27-
it('Parses form url encoded body when charset is also defined in the content-type', () => {
28-
const form = { hello: 'world' };
29-
const headers = { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' };
27+
it("Parses form url encoded body when charset is also defined in the content-type", () => {
28+
const form = { hello: "world" };
29+
const headers = { "content-type": "application/x-www-form-urlencoded;charset=UTF-8" };
3030
const body = new Body(stringify(form), headers).getParsedBody();
3131
expect(body).toEqual(form);
3232
});
3333

3434
it("Tries to parse body as JSON when content type isn't specified", () => {
35-
const json = { hello: 'world' };
35+
const json = { hello: "world" };
3636
const headers = undefined;
3737
const body = new Body(JSON.stringify(json), headers).getParsedBody();
3838
expect(body).toEqual(json);
3939
});
4040

4141
it("Errors when encoding and content-type don't match", () => {
4242
const invalid = '2["test" : 123]4}{';
43-
const headers = { 'content-type': 'application/json' };
43+
const headers = { "content-type": "application/json" };
4444
const body = new Body(invalid, headers).getParsedBody();
4545
expect(body).toEqual(invalid);
4646
});
4747

48-
it('Returns empty body when none given', () => {
48+
it("Returns empty body when none given", () => {
4949
let empty;
50-
const headers = { 'content-type': 'application/x-www-form-urlencoded' };
50+
const headers = { "content-type": "application/x-www-form-urlencoded" };
5151
const body = new Body(empty, headers).getParsedBody();
5252
expect(body).toEqual(empty);
5353
});
5454
});
5555

56-
describe('Request parsing', () => {
57-
it('Gets all fields with optional parameters', () => {
56+
describe("Request parsing", () => {
57+
it("Gets all fields with optional parameters", () => {
5858
const event = apiGatewayEvent({
59-
body: JSON.stringify({ hello: 'world' }),
60-
pathParameters: { proxy: 'not today' },
61-
queryStringParameters: { name: 'a test' },
62-
headers: { 'content-type': 'application/json', 'Test-Request': 'true' },
59+
body: JSON.stringify({ hello: "world" }),
60+
pathParameters: { proxy: "not today" },
61+
queryStringParameters: { name: "a test" },
62+
headers: { "content-type": "application/json", "test-request": "true" },
6363
});
6464
const { body, path, query, auth, headers, testRequest } = new Request(event).getProperties();
6565

66-
expect(body).toEqual({ hello: 'world' });
67-
expect(path).toEqual({ proxy: 'not today' });
68-
expect(query).toEqual({ name: 'a test' });
69-
expect(headers['content-type']).toEqual('application/json');
66+
expect(body).toEqual({ hello: "world" });
67+
expect(path).toEqual({ proxy: "not today" });
68+
expect(query).toEqual({ name: "a test" });
69+
expect(headers["content-type"]).toEqual("application/json");
7070
expect(testRequest).toEqual(true);
7171
expect(auth).toBeTruthy();
7272
});
@@ -87,7 +87,7 @@ describe('Request parsing', () => {
8787
expect(testRequest).toBeFalsy();
8888
});
8989

90-
it('Supports default values in method signature', () => {
90+
it("Supports default values in method signature", () => {
9191
const event = apiGatewayEvent();
9292
delete event.body;
9393
delete event.headers;

src/api/v1/parser.ts

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { APIGatewayEvent } from 'aws-lambda';
2-
import { parse } from 'querystring';
3-
import { Metrics, logger } from '../../common';
1+
import { APIGatewayEvent } from "aws-lambda";
2+
import { parse } from "querystring";
3+
import { Metrics, logger } from "../../common";
44

5-
const metrics = new Metrics('API Gateway');
5+
const metrics = new Metrics("API Gateway");
66

77
export class Request {
88
constructor(private event: APIGatewayEvent) {}
@@ -15,7 +15,7 @@ export class Request {
1515
const auth = this.getAuth();
1616
const headers = event.headers ? event.headers : undefined;
1717
const body = new Body(event.body, headers).getParsedBody();
18-
const TEST_REQUEST_HEADER = process.env.TEST_REQUEST_HEADER || 'Test-Request';
18+
const TEST_REQUEST_HEADER = process.env.TEST_REQUEST_HEADER || "test-request";
1919
const testRequest = headers && headers[TEST_REQUEST_HEADER] ? JSON.parse(headers[TEST_REQUEST_HEADER]) : false;
2020
const parsed = { body, websocket, path, query, auth, headers, testRequest };
2121
metrics.common(parsed, event);
@@ -24,6 +24,7 @@ export class Request {
2424

2525
private getAuth() {
2626
const authorizer = this.event?.requestContext?.authorizer;
27+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
2728
// @ts-ignore
2829
const httpApiAuth = this.event.auth;
2930
return authorizer ? authorizer : httpApiAuth;
@@ -43,11 +44,11 @@ export class Body {
4344
} else if (this.isJSON(contentType)) {
4445
parsedBody = JSON.parse(this.body);
4546
} else {
46-
logger.error('Content-Type header not found, attempting to parse as JSON');
47+
logger.error("Content-Type header not found, attempting to parse as JSON");
4748
parsedBody = JSON.parse(this.body);
4849
}
4950
} catch (err) {
50-
logger.error('Error parsing body, returning as-is', err, this.body);
51+
logger.error("Error parsing body, returning as-is", err, this.body);
5152
parsedBody = this.body;
5253
}
5354
}
@@ -56,15 +57,15 @@ export class Body {
5657

5758
private getContentType(): string {
5859
return (
59-
this.headers && (this.headers['Content-Type'] || this.headers['CONTENT-TYPE'] || this.headers['content-type'])
60+
this.headers && (this.headers["Content-Type"] || this.headers["CONTENT-TYPE"] || this.headers["content-type"])
6061
);
6162
}
6263

6364
private isFormUrlEncoded(contentType?: string): boolean {
64-
return contentType?.toUpperCase().includes('APPLICATION/X-WWW-FORM-URLENCODED');
65+
return contentType?.toUpperCase().includes("APPLICATION/X-WWW-FORM-URLENCODED");
6566
}
6667

6768
private isJSON(contentType: string): boolean {
68-
return contentType?.toUpperCase().includes('APPLICATION/JSON');
69+
return contentType?.toUpperCase().includes("APPLICATION/JSON");
6970
}
7071
}

src/api/v1/wrapper.test.ts

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,34 @@
11
/* eslint-disable @typescript-eslint/no-empty-function */
2-
import { apiGatewayEvent } from 'serverless-plugin-test-helper';
3-
import { api, ApiSignature } from './wrapper';
2+
import { apiGatewayEvent } from "serverless-plugin-test-helper";
3+
import { api, ApiSignature } from "./wrapper";
44

5-
describe('API wrapper', () => {
5+
describe("API wrapper", () => {
66
const requestEvent = apiGatewayEvent({
7-
body: JSON.stringify({ hello: 'world' }),
8-
pathParameters: { proxy: 'not today' },
9-
queryStringParameters: { name: 'a test' },
10-
headers: { 'content-type': 'application/json', 'Test-Request': 'true' },
7+
body: JSON.stringify({ hello: "world" }),
8+
pathParameters: { proxy: "not today" },
9+
queryStringParameters: { name: "a test" },
10+
headers: { "content-type": "application/json", "test-request": "true" },
1111
requestContext: {
12-
connectionId: 'abc-123',
12+
connectionId: "abc-123",
1313
},
1414
});
1515
const context = {
1616
callbackWaitsForEmptyEventLoop: false,
17-
functionName: 'function-name',
18-
functionVersion: '$LATEST',
19-
invokedFunctionArn: 'arn:',
20-
memoryLimitInMB: '128',
21-
awsRequestId: 'request',
22-
logGroupName: 'group',
23-
logStreamName: 'stream',
17+
functionName: "function-name",
18+
functionVersion: "$LATEST",
19+
invokedFunctionArn: "arn:",
20+
memoryLimitInMB: "128",
21+
awsRequestId: "request",
22+
logGroupName: "group",
23+
logStreamName: "stream",
2424
getRemainingTimeInMillis: () => 2,
2525
done: () => {},
2626
fail: () => {},
2727
succeed: () => {},
2828
};
2929
const callback = jest.fn((err, result) => (err ? new Error(err) : result));
3030

31-
it('Has expected properties and response functions', () => {
31+
it("Has expected properties and response functions", () => {
3232
function customHandler({
3333
event,
3434
websocket,
@@ -47,11 +47,11 @@ describe('API wrapper', () => {
4747
custom,
4848
}: ApiSignature) {
4949
expect(event).toEqual(requestEvent);
50-
expect(websocket.connectionId).toEqual('abc-123');
51-
expect(body).toEqual({ hello: 'world' });
52-
expect(path).toEqual({ proxy: 'not today' });
53-
expect(query).toEqual({ name: 'a test' });
54-
expect(headers['content-type']).toEqual('application/json');
50+
expect(websocket.connectionId).toEqual("abc-123");
51+
expect(body).toEqual({ hello: "world" });
52+
expect(path).toEqual({ proxy: "not today" });
53+
expect(query).toEqual({ name: "a test" });
54+
expect(headers["content-type"]).toEqual("application/json");
5555
expect(testRequest).toEqual(true);
5656
expect(auth).toBeTruthy();
5757
expect(success).toBeInstanceOf(Function);
@@ -61,12 +61,12 @@ describe('API wrapper', () => {
6161
expect(redirect).toBeInstanceOf(Function);
6262
expect(error).toBeInstanceOf(Function);
6363
expect(custom).toBeInstanceOf(Function);
64-
success({ body: 'success' });
64+
success({ body: "success" });
6565
}
6666
api(customHandler)(requestEvent, context, callback);
6767
});
6868

69-
it('Has expected properties and response functions with optional generic type', () => {
69+
it("Has expected properties and response functions with optional generic type", () => {
7070
interface CustomType {
7171
Message: string;
7272
Id: number;
@@ -89,11 +89,11 @@ describe('API wrapper', () => {
8989
custom,
9090
}: ApiSignature<CustomType>) {
9191
expect(event).toEqual(requestEvent);
92-
expect(websocket.connectionId).toEqual('abc-123');
93-
expect(body).toEqual({ hello: 'world' });
94-
expect(path).toEqual({ proxy: 'not today' });
95-
expect(query).toEqual({ name: 'a test' });
96-
expect(headers['content-type']).toEqual('application/json');
92+
expect(websocket.connectionId).toEqual("abc-123");
93+
expect(body).toEqual({ hello: "world" });
94+
expect(path).toEqual({ proxy: "not today" });
95+
expect(query).toEqual({ name: "a test" });
96+
expect(headers["content-type"]).toEqual("application/json");
9797
expect(testRequest).toEqual(true);
9898
expect(auth).toBeTruthy();
9999
expect(success).toBeInstanceOf(Function);
@@ -103,7 +103,7 @@ describe('API wrapper', () => {
103103
expect(redirect).toBeInstanceOf(Function);
104104
expect(error).toBeInstanceOf(Function);
105105
expect(custom).toBeInstanceOf(Function);
106-
success({ body: 'success' });
106+
success({ body: "success" });
107107
}
108108
api(customHandler)(requestEvent, context, callback);
109109
});

0 commit comments

Comments
 (0)