Skip to content

Commit 26cee59

Browse files
author
Alexander Melnyk
committed
simplify test
1 parent b4bd495 commit 26cee59

File tree

1 file changed

+34
-26
lines changed

1 file changed

+34
-26
lines changed
Lines changed: 34 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,19 @@
11
import { addUserAgentMiddleware } from '../../src/middleware/userAgentMiddleware';
22
import { InvokeCommand, LambdaClient } from '@aws-sdk/client-lambda';
33

4+
/**
5+
* Logs request headers
6+
*
7+
* This is a middleware we use to test
8+
*/
9+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
10+
// @ts-ignore
11+
const logHeadersMiddleware = (next, _context) => async (args) => {
12+
console.log(args.request.headers);
13+
14+
return await next(args);
15+
};
16+
417
describe('Function: addUserAgentMiddleware', () => {
518
it('adds powertools user agent to request header at the end', async () => {
619
const lambdaClient = new LambdaClient({
@@ -9,41 +22,36 @@ describe('Function: addUserAgentMiddleware', () => {
922
endpoint: 'http://localhost:9001',
1023
maxAttempts: 1, // disable retry to have the correct number of assertions
1124
});
25+
26+
// Set a spy on the console.log method, so we can check the headers
27+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
28+
1229
addUserAgentMiddleware(lambdaClient, 'my-feature');
1330

1431
expect(lambdaClient.middlewareStack.identify()).toContain(
1532
'addPowertoolsToUserAgent: POWERTOOLS,USER_AGENT'
1633
);
1734

18-
lambdaClient.middlewareStack.add(
19-
(next) => (args) => {
20-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
21-
// @ts-ignore
22-
const userAgent = args?.request?.headers['user-agent'];
23-
expect(userAgent).toContain('PT/my-feature/1.10.0 PTEnv/NA');
24-
// make sure it's at the end of the user agent
25-
expect(
26-
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
27-
// @ts-ignore
28-
userAgent
29-
?.split(' ')
30-
.slice(userAgent?.split(' ').length - 2)
31-
.join(' ')
32-
).toEqual('PT/my-feature/1.10.0 PTEnv/NA');
33-
34-
return next(args);
35-
},
36-
{
37-
step: 'finalizeRequest',
38-
}
39-
);
40-
try {
41-
await lambdaClient.send(
35+
lambdaClient.middlewareStack.addRelativeTo(logHeadersMiddleware, {
36+
relation: 'after',
37+
toMiddleware: 'addPowertoolsToUserAgent',
38+
name: 'logHeadersMiddleware',
39+
tags: ['TEST'],
40+
});
41+
42+
await expect(() =>
43+
lambdaClient.send(
4244
new InvokeCommand({
4345
FunctionName: 'test',
4446
Payload: new TextEncoder().encode(JSON.stringify('foo')),
4547
})
46-
);
47-
} catch (e) {}
48+
)
49+
).rejects.toThrow();
50+
51+
expect(consoleSpy).toHaveBeenCalledWith(
52+
expect.objectContaining({
53+
'user-agent': expect.stringContaining('PT/my-feature/1.10.0 PTEnv/NA'),
54+
})
55+
);
4856
});
4957
});

0 commit comments

Comments
 (0)