1
1
import { addUserAgentMiddleware } from '../../src/middleware/userAgentMiddleware' ;
2
2
import { InvokeCommand , LambdaClient } from '@aws-sdk/client-lambda' ;
3
3
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
+
4
17
describe ( 'Function: addUserAgentMiddleware' , ( ) => {
5
18
it ( 'adds powertools user agent to request header at the end' , async ( ) => {
6
19
const lambdaClient = new LambdaClient ( {
@@ -9,41 +22,36 @@ describe('Function: addUserAgentMiddleware', () => {
9
22
endpoint : 'http://localhost:9001' ,
10
23
maxAttempts : 1 , // disable retry to have the correct number of assertions
11
24
} ) ;
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
+
12
29
addUserAgentMiddleware ( lambdaClient , 'my-feature' ) ;
13
30
14
31
expect ( lambdaClient . middlewareStack . identify ( ) ) . toContain (
15
32
'addPowertoolsToUserAgent: POWERTOOLS,USER_AGENT'
16
33
) ;
17
34
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 (
42
44
new InvokeCommand ( {
43
45
FunctionName : 'test' ,
44
46
Payload : new TextEncoder ( ) . encode ( JSON . stringify ( 'foo' ) ) ,
45
47
} )
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
+ ) ;
48
56
} ) ;
49
57
} ) ;
0 commit comments