Skip to content

Commit bc5e469

Browse files
authored
feat: add tests and fix env
1 parent f9cfb2c commit bc5e469

9 files changed

+6166
-2756
lines changed

.env.template

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,6 @@ HOST=0.0.0.0
99
# Auth lib
1010
AUTH_URL=http://localhost:8080
1111
KEYCLOAK_REALM=tazama
12-
CERT_PATH=private-key.pem
12+
CERT_PATH_PRIVATE=private-key.pem
1313
CLIENT_SECRET=
1414
CLIENT_ID=

.husky/pre-push

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
npm test

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ A [registry](https://github.com/frmscoe/docs) of environment variables is provid
3030
| `KEYCLOAK_REALM` | KeyCloak Realm for Tazama | `tazama`
3131
| `CLIENT_ID` | KeyCloak defined client for auth-lib | `auth-lib-client`
3232
| `CLIENT_SECRET` | The secret of the KeyCloak client | `someClientGeneratedSecret123`
33-
| `CERT_PATH` | The pem file path for signing Tazama tokens | `/path/to/private-key.pem`
33+
| `CERT_PATH_PRIVATE` | The pem file path for signing Tazama tokens | `/path/to/private-key.pem`
3434

3535
#### Build and Start
3636

__tests__/unit/app.test.ts

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { AuthenticationService } from '@frmscoe/auth-lib';
2+
import { getTazamaToken } from '../../src/logic.service';
3+
4+
// AuthenticationService mocked in jest.setup.ts
5+
6+
describe('App Services', () => {
7+
it('should handle getToken from library - happy path', async () => {
8+
const authBody = {
9+
username: 'user',
10+
password: 'password',
11+
};
12+
13+
const tazamaToken = await getTazamaToken(authBody);
14+
15+
expect(typeof tazamaToken).toEqual('string');
16+
expect(tazamaToken).toBeDefined();
17+
});
18+
19+
it('should handle getToken from library - blank token', async () => {
20+
const authBody = {
21+
username: 'blank',
22+
password: 'password',
23+
};
24+
25+
try {
26+
await getTazamaToken(authBody);
27+
throw new Error('UNREACHABLE');
28+
} catch (err) {
29+
expect(err).toEqual(new Error('getTazamaToken retrieval failed'));
30+
}
31+
});
32+
33+
it('should handle getToken from library - error from getToken', async () => {
34+
const authBody = {
35+
username: 'reject',
36+
password: 'password',
37+
};
38+
39+
try {
40+
await getTazamaToken(authBody);
41+
throw new Error('UNREACHABLE');
42+
} catch (err) {
43+
expect(err).toEqual(new Error('getTazamaToken retrieval failed'));
44+
}
45+
});
46+
});

eslint.config.mjs

+1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ export default [
4949
'**/node_modules/**',
5050
'**/__tests__/**',
5151
'**/jest.config.ts',
52+
'**/jest.setup.ts',
5253
'**/cluster-setup.ts',
5354
],
5455
}

jest.config.ts

+215
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
/*
4+
* For a detailed explanation regarding each configuration property and type check, visit:
5+
* https://jestjs.io/docs/en/configuration.html
6+
*/
7+
8+
import type { Config } from '@jest/types';
9+
10+
// Sync object
11+
const config: Config.InitialOptions = {
12+
// All imported modules in your tests should be mocked automatically
13+
// automock: false,
14+
15+
// Stop running tests after `n` failures
16+
bail: 1,
17+
18+
// The directory where Jest should store its cached dependency information
19+
// cacheDirectory: "/private/var/folders/fv/vk9htm4s40xd4pb2lm_3tbym0000gn/T/jest_dx",
20+
21+
// Automatically clear mock calls and instances between every test
22+
clearMocks: true,
23+
24+
// Indicates whether the coverage information should be collected while executing the test
25+
collectCoverage: true,
26+
27+
// An array of glob patterns indicating a set of files for which coverage information should be collected
28+
collectCoverageFrom: ['src/logic.service.ts'],
29+
30+
// The directory where Jest should output its coverage files
31+
coverageDirectory: '<rootDir>/coverage/',
32+
33+
// An array of regexp pattern strings used to skip coverage collection
34+
coveragePathIgnorePatterns: [
35+
'/node_modules/',
36+
'./src/interfaces',
37+
'./src/models',
38+
'./__tests__',
39+
'interfaces',
40+
'.module.ts',
41+
'.mock.ts',
42+
'./src/index.ts',
43+
'./src/clients/arangodb.ts',
44+
'./src/clients/index.ts',
45+
'./src/clients/redis.ts',
46+
'./router.ts',
47+
'./jest.config.ts',
48+
],
49+
50+
// Indicates which provider should be used to instrument code for coverage
51+
coverageProvider: 'v8',
52+
53+
// A list of reporter names that Jest uses when writing coverage reports
54+
// coverageReporters: [
55+
// "json",
56+
// "text",
57+
// "lcov",
58+
// "clover"
59+
// ],
60+
61+
// An object that configures minimum threshold enforcement for coverage results
62+
coverageThreshold: {
63+
global: {
64+
branches: 95,
65+
functions: 95,
66+
lines: 95,
67+
statements: 95,
68+
},
69+
},
70+
71+
// A path to a custom dependency extractor
72+
// dependencyExtractor: undefined,
73+
74+
// Make calling deprecated APIs throw helpful error messages
75+
errorOnDeprecated: false,
76+
77+
// Force coverage collection from ignored files using an array of glob patterns
78+
// forceCoverageMatch: [],
79+
80+
// A path to a module which exports an async function that is triggered once before all test suites
81+
// globalSetup: undefined,
82+
83+
// A path to a module which exports an async function that is triggered once after all test suites
84+
// globalTeardown: undefined,
85+
86+
// A set of global variables that need to be available in all test environments
87+
// globals: {},
88+
89+
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
90+
// maxWorkers: "50%",
91+
92+
// An array of directory names to be searched recursively up from the requiring module's location
93+
// moduleDirectories: [
94+
// "node_modules"
95+
// ],
96+
97+
// An array of file extensions your modules use
98+
// moduleFileExtensions: [
99+
// "js",
100+
// "json",
101+
// "jsx",
102+
// "ts",
103+
// "tsx",
104+
// "node"
105+
// ],
106+
107+
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
108+
// moduleNameMapper: {},
109+
110+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
111+
// modulePathIgnorePatterns: [],
112+
113+
// Activates notifications for test results
114+
notify: false,
115+
116+
// An enum that specifies notification mode. Requires { notify: true }
117+
// notifyMode: "failure-change",
118+
119+
// A preset that is used as a base for Jest's configuration
120+
preset: 'ts-jest',
121+
122+
// Run tests from one or more projects
123+
// projects: undefined,
124+
125+
// Use this configuration option to add custom reporters to Jest
126+
// reporters: undefined,
127+
128+
// Automatically reset mock state between every test
129+
resetMocks: true,
130+
131+
// Reset the module registry before running each individual test
132+
// resetModules: false,
133+
134+
// A path to a custom resolver
135+
// resolver: undefined,
136+
137+
// Automatically restore mock state between every test
138+
// restoreMocks: false,
139+
140+
// The root directory that Jest should scan for tests and modules within
141+
// rootDir: ".",
142+
143+
// A list of paths to directories that Jest should use to search for files in
144+
roots: ['<rootDir>/__tests__/'],
145+
146+
// Allows you to use a custom runner instead of Jest's default test runner
147+
// runner: "jest-runner",
148+
149+
// The paths to modules that run some code to configure or set up the testing environment before each test
150+
//setupFiles: ['dotenv/config'],
151+
152+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
153+
setupFilesAfterEnv: ['./jest.setup.ts'],
154+
155+
// The number of seconds after which a test is considered as slow and reported as such in the results.
156+
// slowTestThreshold: 5,
157+
158+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
159+
// snapshotSerializers: [],
160+
161+
// The test environment that will be used for testing
162+
testEnvironment: 'node',
163+
164+
// Options that will be passed to the testEnvironment
165+
// testEnvironmentOptions: {},
166+
167+
// Adds a location field to test results
168+
// testLocationInResults: false,
169+
170+
// The glob patterns Jest uses to detect test files
171+
testMatch: ['**/*.test.ts'],
172+
173+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
174+
testPathIgnorePatterns: ['/node_modules/'],
175+
176+
// The regexp pattern or array of patterns that Jest uses to detect test files
177+
// testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(ts|js)$',
178+
179+
// This option allows the use of a custom results processor
180+
// testResultsProcessor: undefined,
181+
182+
// This option allows use of a custom test runner
183+
// testRunner: "jasmine2",
184+
185+
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
186+
// testURL: "http://localhost",
187+
188+
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
189+
// timers: "real",
190+
191+
// A map from regular expressions to paths to transformers
192+
transform: {
193+
'^.+\\.ts$': 'ts-jest',
194+
},
195+
196+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
197+
// transformIgnorePatterns: [
198+
// "/node_modules/",
199+
// "\\.pnp\\.[^\\/]+$"
200+
// ],
201+
202+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
203+
// unmockedModulePathPatterns: undefined,
204+
205+
// Indicates whether each individual test should be reported during the run
206+
verbose: true,
207+
208+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
209+
// watchPathIgnorePatterns: [],
210+
211+
// Whether to use watchman for file crawling
212+
// watchman: true,
213+
};
214+
215+
export default config;

jest.setup.ts

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const authLib = jest.requireActual('@frmscoe/auth-lib');
2+
3+
class MockAuthenticationService {
4+
getToken(u: string, p: string): Promise<string> {
5+
if (u === 'blank') {
6+
return Promise.resolve('');
7+
} else if (u === 'reject') {
8+
return Promise.reject('REJECT');
9+
} else {
10+
return Promise.resolve(`${u}${p}`);
11+
}
12+
}
13+
}
14+
15+
const mockedAuthLib = { ...authLib, AuthenticationService: MockAuthenticationService };
16+
17+
jest.mock('@frmscoe/auth-lib', () => mockedAuthLib);

0 commit comments

Comments
 (0)