1
- // import supertest from 'supertest';
2
- // import app from '../../src/app';
3
- // import apikey from '../../src/auth/apikey';
1
+ import supertest from 'supertest' ;
2
+ import app from '../../src/app' ;
3
+ import ApiKeyRepo from '../../src/database/repository/ApiKeyRepo' ;
4
+ import { IApiKey } from '../../src/database/model/ApiKey' ;
4
5
5
- // describe('apikey validation', () => {
6
+ describe ( 'apikey validation' , ( ) => {
6
7
7
- // it.
8
- // });
8
+ const request = supertest ( app ) ;
9
+ const API_KEY = 'abc' ;
10
+
11
+ const mockFindApiKey = jest . fn ( async key => {
12
+ if ( key == API_KEY ) return < IApiKey > { key : API_KEY } ;
13
+ else return null ;
14
+ } ) ;
15
+
16
+ ApiKeyRepo . findByKey = mockFindApiKey ;
17
+
18
+ beforeEach ( ( ) => {
19
+ mockFindApiKey . mockClear ( ) ;
20
+ } ) ;
21
+
22
+ it ( 'Should fail with 400 if api-key header is not passed' , async ( ) => {
23
+ const response = await request . get ( '/v1/test' ) ;
24
+ expect ( response . status ) . toBe ( 400 ) ;
25
+ expect ( mockFindApiKey ) . toBeCalledTimes ( 0 ) ;
26
+ } ) ;
27
+
28
+ it ( 'Should fail with 403 if wrong api-key header is passed' , async ( ) => {
29
+ const wrongApiKey = '123' ;
30
+ const response = await request
31
+ . get ( '/v1' )
32
+ . set ( 'x-api-key' , wrongApiKey ) ;
33
+ expect ( response . status ) . toBe ( 403 ) ;
34
+ expect ( mockFindApiKey ) . toBeCalledTimes ( 1 ) ;
35
+ expect ( mockFindApiKey ) . toBeCalledWith ( wrongApiKey ) ;
36
+ } ) ;
37
+
38
+ it ( 'Should pass with 404 if correct api-key header is passed and when route is not handelled' , async ( ) => {
39
+ const response = await request
40
+ . get ( '/v1' )
41
+ . set ( 'x-api-key' , API_KEY ) ;
42
+ expect ( response . status ) . toBe ( 404 ) ;
43
+ expect ( mockFindApiKey ) . toBeCalledTimes ( 1 ) ;
44
+ expect ( mockFindApiKey ) . toBeCalledWith ( API_KEY ) ;
45
+ } ) ;
46
+ } ) ;
0 commit comments