@navios/core 1.0.0 → 2.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/CHANGELOG.md +97 -11
  2. package/README.md +67 -220
  3. package/lib/async-context-6pdlnNLA.d.mts +237 -0
  4. package/lib/async-context-6pdlnNLA.d.mts.map +1 -0
  5. package/lib/async-context-Dqk7pE-D.d.cts +237 -0
  6. package/lib/async-context-Dqk7pE-D.d.cts.map +1 -0
  7. package/lib/attribute-factory-B3VuYnp7.d.cts +70 -0
  8. package/lib/attribute-factory-B3VuYnp7.d.cts.map +1 -0
  9. package/lib/attribute-factory-mKOXoVnV.d.mts +70 -0
  10. package/lib/attribute-factory-mKOXoVnV.d.mts.map +1 -0
  11. package/lib/attribute-value-CjX9ZkLq.cjs +172 -0
  12. package/lib/attribute-value-CjX9ZkLq.cjs.map +1 -0
  13. package/lib/attribute-value-DMEA255r.mjs +119 -0
  14. package/lib/attribute-value-DMEA255r.mjs.map +1 -0
  15. package/lib/basic-execution-context-CeGuhMOz.mjs +246 -0
  16. package/lib/basic-execution-context-CeGuhMOz.mjs.map +1 -0
  17. package/lib/basic-execution-context-DSk5MNtc.cjs +281 -0
  18. package/lib/basic-execution-context-DSk5MNtc.cjs.map +1 -0
  19. package/lib/execution-context-BPD3FeFb.d.mts +71 -0
  20. package/lib/execution-context-BPD3FeFb.d.mts.map +1 -0
  21. package/lib/execution-context-BTJdHhbf.d.cts +71 -0
  22. package/lib/execution-context-BTJdHhbf.d.cts.map +1 -0
  23. package/lib/execution-context-token-BXUKB2hf.cjs +112 -0
  24. package/lib/execution-context-token-BXUKB2hf.cjs.map +1 -0
  25. package/lib/execution-context-token-CrXmTvk2.mjs +77 -0
  26. package/lib/execution-context-token-CrXmTvk2.mjs.map +1 -0
  27. package/lib/index.cjs +1687 -4409
  28. package/lib/index.cjs.map +1 -1
  29. package/lib/index.d.cts +838 -3
  30. package/lib/index.d.cts.map +1 -0
  31. package/lib/index.d.mts +838 -3
  32. package/lib/index.d.mts.map +1 -0
  33. package/lib/index.mjs +1573 -4219
  34. package/lib/index.mjs.map +1 -1
  35. package/lib/legacy-compat/index.cjs +72 -371
  36. package/lib/legacy-compat/index.cjs.map +1 -1
  37. package/lib/legacy-compat/index.d.cts +42 -382
  38. package/lib/legacy-compat/index.d.cts.map +1 -1
  39. package/lib/legacy-compat/index.d.mts +41 -382
  40. package/lib/legacy-compat/index.d.mts.map +1 -1
  41. package/lib/legacy-compat/index.mjs +51 -345
  42. package/lib/legacy-compat/index.mjs.map +1 -1
  43. package/lib/module-Bha7GER_.mjs +135 -0
  44. package/lib/module-Bha7GER_.mjs.map +1 -0
  45. package/lib/module-DZewk_2r.cjs +164 -0
  46. package/lib/module-DZewk_2r.cjs.map +1 -0
  47. package/lib/module-graph-DCP9MHG0.cjs +147 -0
  48. package/lib/module-graph-DCP9MHG0.cjs.map +1 -0
  49. package/lib/module-graph-xvVEykFM.mjs +142 -0
  50. package/lib/module-graph-xvVEykFM.mjs.map +1 -0
  51. package/lib/module-metadata-C8S92seK.cjs +95 -0
  52. package/lib/module-metadata-C8S92seK.cjs.map +1 -0
  53. package/lib/module-metadata-k3RTt20x.mjs +66 -0
  54. package/lib/module-metadata-k3RTt20x.mjs.map +1 -0
  55. package/lib/module-options-Dmse0gii.d.mts +51 -0
  56. package/lib/module-options-Dmse0gii.d.mts.map +1 -0
  57. package/lib/module-options-IuDO-p8u.d.cts +51 -0
  58. package/lib/module-options-IuDO-p8u.d.cts.map +1 -0
  59. package/lib/testing/index.cjs +96 -414
  60. package/lib/testing/index.cjs.map +1 -1
  61. package/lib/testing/index.d.cts +25 -385
  62. package/lib/testing/index.d.cts.map +1 -1
  63. package/lib/testing/index.d.mts +24 -385
  64. package/lib/testing/index.d.mts.map +1 -1
  65. package/lib/testing/index.mjs +94 -408
  66. package/lib/testing/index.mjs.map +1 -1
  67. package/lib/transport.cjs +25 -0
  68. package/lib/transport.d.cts +190 -0
  69. package/lib/transport.d.cts.map +1 -0
  70. package/lib/transport.d.mts +190 -0
  71. package/lib/transport.d.mts.map +1 -0
  72. package/lib/transport.mjs +7 -0
  73. package/package.json +37 -17
  74. package/docs/README.md +0 -316
  75. package/docs/adapters.md +0 -308
  76. package/docs/application-setup.md +0 -524
  77. package/docs/attributes.md +0 -689
  78. package/docs/controllers.md +0 -373
  79. package/docs/endpoints.md +0 -444
  80. package/docs/exceptions.md +0 -352
  81. package/docs/guards.md +0 -550
  82. package/docs/legacy-compat.md +0 -356
  83. package/docs/modules.md +0 -377
  84. package/docs/quick-start.md +0 -290
  85. package/docs/services.md +0 -427
  86. package/docs/testing.md +0 -827
  87. package/lib/index-C0Sg16Eb.d.cts +0 -3365
  88. package/lib/index-C0Sg16Eb.d.cts.map +0 -1
  89. package/lib/index-DySQ6Dpd.d.mts +0 -3365
  90. package/lib/index-DySQ6Dpd.d.mts.map +0 -1
  91. package/lib/navios.factory-CO5MB_OK.cjs +0 -4125
  92. package/lib/navios.factory-CO5MB_OK.cjs.map +0 -1
  93. package/lib/navios.factory-D6Y94P9B.mjs +0 -3828
  94. package/lib/navios.factory-D6Y94P9B.mjs.map +0 -1
  95. package/lib/tokens-4J9sredA.mjs +0 -100
  96. package/lib/tokens-4J9sredA.mjs.map +0 -1
  97. package/lib/tokens-CWw9kyeD.cjs +0 -196
  98. package/lib/tokens-CWw9kyeD.cjs.map +0 -1
  99. package/lib/use-guards.decorator-BecoQSmE.mjs +0 -339
  100. package/lib/use-guards.decorator-BecoQSmE.mjs.map +0 -1
  101. package/lib/use-guards.decorator-C4ml9XaT.cjs +0 -447
  102. package/lib/use-guards.decorator-C4ml9XaT.cjs.map +0 -1
  103. package/project.json +0 -66
  104. package/src/__tests__/attribute.factory.spec.mts +0 -300
  105. package/src/__tests__/config.service.spec.mts +0 -43
  106. package/src/__tests__/console-logger.service.spec.mts +0 -312
  107. package/src/__tests__/controller-resolver.spec.mts +0 -229
  108. package/src/__tests__/controller.spec.mts +0 -58
  109. package/src/__tests__/guard-runner.service.spec.mts +0 -399
  110. package/src/__tests__/logger.service.spec.mts +0 -147
  111. package/src/__tests__/responders.spec.mts +0 -340
  112. package/src/__tests__/testing-module.spec.mts +0 -459
  113. package/src/__tests__/unit-testing-module.spec.mts +0 -424
  114. package/src/attribute.factory.mts +0 -325
  115. package/src/config/config-service.interface.mts +0 -47
  116. package/src/config/config.provider.mts +0 -69
  117. package/src/config/config.service.mts +0 -176
  118. package/src/config/index.mts +0 -5
  119. package/src/config/types.mts +0 -58
  120. package/src/config/utils/helpers.mts +0 -23
  121. package/src/config/utils/index.mts +0 -1
  122. package/src/decorators/controller.decorator.mts +0 -81
  123. package/src/decorators/endpoint.decorator.mts +0 -181
  124. package/src/decorators/header.decorator.mts +0 -38
  125. package/src/decorators/http-code.decorator.mts +0 -38
  126. package/src/decorators/index.mts +0 -8
  127. package/src/decorators/module.decorator.mts +0 -106
  128. package/src/decorators/multipart.decorator.mts +0 -169
  129. package/src/decorators/stream.decorator.mts +0 -155
  130. package/src/decorators/use-guards.decorator.mts +0 -73
  131. package/src/exceptions/bad-request.exception.mts +0 -28
  132. package/src/exceptions/conflict.exception.mts +0 -31
  133. package/src/exceptions/forbidden.exception.mts +0 -30
  134. package/src/exceptions/http.exception.mts +0 -33
  135. package/src/exceptions/index.mts +0 -7
  136. package/src/exceptions/internal-server-error.exception.mts +0 -33
  137. package/src/exceptions/not-found.exception.mts +0 -33
  138. package/src/exceptions/unauthorized.exception.mts +0 -30
  139. package/src/factories/adapter.factory.mts +0 -20
  140. package/src/factories/endpoint-adapter.factory.mts +0 -21
  141. package/src/factories/http-adapter.factory.mts +0 -20
  142. package/src/factories/index.mts +0 -8
  143. package/src/factories/multipart-adapter.factory.mts +0 -21
  144. package/src/factories/reply.factory.mts +0 -21
  145. package/src/factories/request.factory.mts +0 -21
  146. package/src/factories/stream-adapter.factory.mts +0 -20
  147. package/src/factories/xml-stream-adapter.factory.mts +0 -20
  148. package/src/index.mts +0 -16
  149. package/src/interfaces/abstract-adapter.interface.mts +0 -32
  150. package/src/interfaces/abstract-execution-context.inteface.mts +0 -48
  151. package/src/interfaces/abstract-http-adapter.interface.mts +0 -79
  152. package/src/interfaces/abstract-http-cors-options.interface.mts +0 -59
  153. package/src/interfaces/abstract-http-handler-adapter.interface.mts +0 -127
  154. package/src/interfaces/abstract-http-listen-options.interface.mts +0 -4
  155. package/src/interfaces/adapter-environment.interface.mts +0 -74
  156. package/src/interfaces/can-activate.mts +0 -38
  157. package/src/interfaces/http-header.mts +0 -18
  158. package/src/interfaces/index.mts +0 -11
  159. package/src/interfaces/navios-module.mts +0 -28
  160. package/src/interfaces/plugin.interface.mts +0 -139
  161. package/src/legacy-compat/__type-tests__/legacy-decorators.spec-d.mts +0 -521
  162. package/src/legacy-compat/__type-tests__/tsconfig.json +0 -15
  163. package/src/legacy-compat/attribute.factory.mts +0 -351
  164. package/src/legacy-compat/decorators/controller.decorator.mts +0 -31
  165. package/src/legacy-compat/decorators/endpoint.decorator.mts +0 -73
  166. package/src/legacy-compat/decorators/header.decorator.mts +0 -43
  167. package/src/legacy-compat/decorators/http-code.decorator.mts +0 -39
  168. package/src/legacy-compat/decorators/index.mts +0 -11
  169. package/src/legacy-compat/decorators/module.decorator.mts +0 -37
  170. package/src/legacy-compat/decorators/multipart.decorator.mts +0 -72
  171. package/src/legacy-compat/decorators/stream.decorator.mts +0 -89
  172. package/src/legacy-compat/decorators/use-guards.decorator.mts +0 -80
  173. package/src/legacy-compat/index.mts +0 -57
  174. package/src/logger/README.md +0 -3
  175. package/src/logger/console-logger.service.mts +0 -714
  176. package/src/logger/index.mts +0 -6
  177. package/src/logger/log-levels.mts +0 -21
  178. package/src/logger/logger-service.interface.mts +0 -42
  179. package/src/logger/logger.service.mts +0 -113
  180. package/src/logger/logger.tokens.mts +0 -44
  181. package/src/logger/utils/cli-colors.util.mts +0 -17
  182. package/src/logger/utils/filter-log-levelts.util.mts +0 -29
  183. package/src/logger/utils/index.mts +0 -5
  184. package/src/logger/utils/is-log-level-enabled.mts +0 -33
  185. package/src/logger/utils/is-log-level.util.mts +0 -10
  186. package/src/logger/utils/shared.utils.mts +0 -51
  187. package/src/metadata/controller.metadata.mts +0 -72
  188. package/src/metadata/handler.metadata.mts +0 -80
  189. package/src/metadata/index.mts +0 -4
  190. package/src/metadata/module.metadata.mts +0 -108
  191. package/src/metadata/navios-managed.metadata.mts +0 -42
  192. package/src/navios.application.mts +0 -484
  193. package/src/navios.environment.mts +0 -42
  194. package/src/navios.factory.mts +0 -158
  195. package/src/responders/enums/framework-error.enum.mts +0 -38
  196. package/src/responders/enums/index.mts +0 -1
  197. package/src/responders/index.mts +0 -4
  198. package/src/responders/interfaces/error-responder.interface.mts +0 -42
  199. package/src/responders/interfaces/error-response.interface.mts +0 -22
  200. package/src/responders/interfaces/index.mts +0 -3
  201. package/src/responders/interfaces/problem-details.interface.mts +0 -34
  202. package/src/responders/services/error-response-producer.service.mts +0 -143
  203. package/src/responders/services/forbidden-responder.service.mts +0 -77
  204. package/src/responders/services/index.mts +0 -5
  205. package/src/responders/services/internal-server-error-responder.service.mts +0 -57
  206. package/src/responders/services/not-found-responder.service.mts +0 -76
  207. package/src/responders/services/validation-error-responder.service.mts +0 -78
  208. package/src/responders/tokens/index.mts +0 -1
  209. package/src/responders/tokens/responder.tokens.mts +0 -84
  210. package/src/services/abstract-handler-adapter.service.mts +0 -366
  211. package/src/services/guard-runner.service.mts +0 -152
  212. package/src/services/index.mts +0 -4
  213. package/src/services/instance-resolver.service.mts +0 -177
  214. package/src/services/module-loader.service.mts +0 -252
  215. package/src/stores/index.mts +0 -1
  216. package/src/stores/request-id.store.mts +0 -85
  217. package/src/testing/index.mts +0 -3
  218. package/src/testing/testing-module.mts +0 -393
  219. package/src/testing/unit-testing-module.mts +0 -298
  220. package/src/tokens/adapter.token.mts +0 -6
  221. package/src/tokens/endpoint-adapter.token.mts +0 -8
  222. package/src/tokens/execution-context.token.mts +0 -9
  223. package/src/tokens/http-adapter.token.mts +0 -8
  224. package/src/tokens/index.mts +0 -10
  225. package/src/tokens/multipart-adapter.token.mts +0 -8
  226. package/src/tokens/navios-options.token.mts +0 -6
  227. package/src/tokens/reply.token.mts +0 -3
  228. package/src/tokens/request.token.mts +0 -3
  229. package/src/tokens/stream-adapter.token.mts +0 -8
  230. package/src/tokens/xml-stream-adapter.token.mts +0 -8
  231. package/src/utils/adapter-supports.util.mts +0 -47
  232. package/src/utils/index.mts +0 -1
  233. package/tsconfig.json +0 -21
  234. package/tsconfig.lib.json +0 -8
  235. package/tsconfig.spec.json +0 -15
  236. package/tsdown.config.mts +0 -35
  237. package/vitest.config.mts +0 -15
package/docs/testing.md DELETED
@@ -1,827 +0,0 @@
1
- # Testing Guide
2
-
3
- This guide covers testing strategies and best practices for Navios applications, including unit testing, integration testing, and end-to-end testing.
4
-
5
- ## Testing Philosophy
6
-
7
- Navios promotes a testing-first approach with:
8
-
9
- - **Unit Tests** - Test individual components in isolation
10
- - **Integration Tests** - Test component interactions
11
- - **End-to-End Tests** - Test complete user workflows
12
-
13
- ## Setting Up Testing
14
-
15
- ### Test Dependencies
16
-
17
- ```bash
18
- npm install --save-dev vitest supertest @navios/builder
19
- ```
20
-
21
- ## Testing Module
22
-
23
- Navios provides a dedicated testing module that simplifies setting up test environments with mock dependencies.
24
-
25
- ### Creating a Testing Module
26
-
27
- The `createTestingModule` function is the main entry point for setting up tests:
28
-
29
- ```typescript
30
- import { createTestingModule } from '@navios/core/testing'
31
-
32
- import { AppModule } from './app.module'
33
- import { DatabaseService } from './database.service'
34
-
35
- describe('AppModule', () => {
36
- it('should create application with mocked dependencies', async () => {
37
- const mockDatabase = {
38
- query: vi.fn().mockResolvedValue([]),
39
- }
40
-
41
- const testingModule = createTestingModule(AppModule, {
42
- adapter: [], // No HTTP adapter for unit tests
43
- })
44
- .overrideProvider(DatabaseService)
45
- .useValue(mockDatabase)
46
-
47
- const app = await testingModule.compile()
48
-
49
- // App is ready to use with mocked DatabaseService
50
- expect(app).toBeDefined()
51
-
52
- await testingModule.close()
53
- })
54
- })
55
- ```
56
-
57
- ### TestingModule API
58
-
59
- #### `createTestingModule(appModule, options)`
60
-
61
- Creates a new testing module builder.
62
-
63
- ```typescript
64
- const testingModule = createTestingModule(AppModule, {
65
- adapter: [], // Required: HTTP adapter configuration
66
- logger: false, // Optional: Disable logging for tests
67
- overrides: [ // Optional: Initial overrides
68
- { token: SomeService, useValue: mockService },
69
- ],
70
- })
71
- ```
72
-
73
- #### `.overrideProvider(token)`
74
-
75
- Returns a builder for overriding a provider:
76
-
77
- ```typescript
78
- testingModule
79
- .overrideProvider(DatabaseService)
80
- .useValue(mockDatabaseService) // Use a mock value
81
-
82
- testingModule
83
- .overrideProvider(CacheService)
84
- .useClass(MockCacheService) // Use a mock class
85
- ```
86
-
87
- #### `.compile()`
88
-
89
- Compiles the testing module and returns the `NaviosApplication`:
90
-
91
- ```typescript
92
- const app = await testingModule.compile()
93
- ```
94
-
95
- #### `.init()`
96
-
97
- Compiles and initializes the application (equivalent to calling `compile()` then `app.init()`):
98
-
99
- ```typescript
100
- const app = await testingModule.init()
101
- ```
102
-
103
- #### `.get(token)`
104
-
105
- Gets an instance from the container:
106
-
107
- ```typescript
108
- const userService = await testingModule.get(UserService)
109
- ```
110
-
111
- #### `.getContainer()`
112
-
113
- Gets the underlying `TestContainer` for direct manipulation:
114
-
115
- ```typescript
116
- const container = testingModule.getContainer()
117
- container.bind(SomeToken).toValue(someValue)
118
- ```
119
-
120
- #### `.close()`
121
-
122
- Disposes the testing module and cleans up resources:
123
-
124
- ```typescript
125
- await testingModule.close()
126
- ```
127
-
128
- ### Custom Container Support
129
-
130
- You can also pass a custom container directly to `NaviosFactory.create()`:
131
-
132
- ```typescript
133
- import { NaviosFactory } from '@navios/core'
134
- import { TestContainer } from '@navios/core/testing'
135
-
136
- const container = new TestContainer()
137
- container.bind(DatabaseService).toValue(mockDatabase)
138
-
139
- const app = await NaviosFactory.create(AppModule, {
140
- adapter: [],
141
- container, // Use custom container
142
- })
143
- ```
144
-
145
- This is useful when you need more control over the container setup or when integrating with existing test infrastructure.
146
-
147
- ## Unit Testing
148
-
149
- ### Testing Services
150
-
151
- ```typescript
152
- import { TestContainer } from '@navios/core/testing'
153
-
154
- import { DatabaseService } from './database.service.js'
155
- import { UserService } from './user.service.js'
156
-
157
- describe('UserService', () => {
158
- let userService: UserService
159
- let mockDatabase: vi.Mocked<DatabaseService>
160
-
161
- beforeEach(() => {
162
- const container = new TestContainer()
163
-
164
- // Create mock database
165
- mockDatabase = {
166
- users: {
167
- findUnique: vi.fn(),
168
- findMany: vi.fn(),
169
- create: vi.fn(),
170
- update: vi.fn(),
171
- delete: vi.fn(),
172
- },
173
- } as any
174
-
175
- container.bind(DatabaseService).toValue(mockDatabase)
176
- userService = container.get(UserService)
177
- })
178
-
179
- describe('findById', () => {
180
- it('should return user when found', async () => {
181
- const mockUser = { id: '1', name: 'John', email: 'john@test.com' }
182
- mockDatabase.users.findUnique.mockResolvedValue(mockUser)
183
-
184
- const result = await userService.findById('1')
185
-
186
- expect(result).toEqual(mockUser)
187
- expect(mockDatabase.users.findUnique).toHaveBeenCalledWith({
188
- where: { id: '1' },
189
- })
190
- })
191
-
192
- it('should return null when user not found', async () => {
193
- mockDatabase.users.findUnique.mockResolvedValue(null)
194
-
195
- const result = await userService.findById('1')
196
-
197
- expect(result).toBeNull()
198
- })
199
- })
200
-
201
- describe('create', () => {
202
- it('should create and return new user', async () => {
203
- const userData = { name: 'John', email: 'john@test.com' }
204
- const createdUser = { id: '1', ...userData }
205
-
206
- mockDatabase.users.create.mockResolvedValue(createdUser)
207
-
208
- const result = await userService.create(userData)
209
-
210
- expect(result).toEqual(createdUser)
211
- expect(mockDatabase.users.create).toHaveBeenCalledWith({
212
- data: userData,
213
- })
214
- })
215
- })
216
- })
217
- ```
218
-
219
- ### Testing Controllers
220
-
221
- Controllers in Navios should use endpoints defined with `@navios/builder` for proper type safety and schema validation.
222
-
223
- #### Endpoint Definitions
224
-
225
- ```typescript
226
- // api/user.endpoints.ts
227
- import { builder } from '@navios/builder'
228
-
229
- import { z } from 'zod'
230
-
231
- const userApi = builder()
232
-
233
- export const getUserByIdEndpoint = userApi.declareEndpoint({
234
- method: 'GET',
235
- url: '/users/$id',
236
- responseSchema: z.object({
237
- id: z.string(),
238
- name: z.string(),
239
- email: z.string().email(),
240
- }),
241
- })
242
-
243
- export const createUserEndpoint = userApi.declareEndpoint({
244
- method: 'POST',
245
- url: '/users',
246
- requestSchema: z.object({
247
- name: z.string().min(1),
248
- email: z.string().email(),
249
- }),
250
- responseSchema: z.object({
251
- id: z.string(),
252
- name: z.string(),
253
- email: z.string().email(),
254
- }),
255
- })
256
- ```
257
-
258
- #### Controller Implementation
259
-
260
- ```typescript
261
- // user.controller.ts
262
- import { Controller, Endpoint, EndpointParams } from '@navios/core'
263
- import { inject } from '@navios/di'
264
-
265
- import { createUserEndpoint, getUserByIdEndpoint } from '../api/user.endpoints'
266
- import { UserService } from './user.service'
267
-
268
- @Controller()
269
- export class UserController {
270
- private userService = inject(UserService)
271
-
272
- @Endpoint(getUserByIdEndpoint)
273
- async getUserById(params: EndpointParams<typeof getUserByIdEndpoint>) {
274
- const user = await this.userService.findById(params.params.id)
275
- if (!user) {
276
- throw new NotFoundException('User not found')
277
- }
278
- return user
279
- }
280
-
281
- @Endpoint(createUserEndpoint)
282
- async createUser(params: EndpointParams<typeof createUserEndpoint>) {
283
- return this.userService.create(params.data)
284
- }
285
- }
286
- ```
287
-
288
- #### Testing Controllers
289
-
290
- ```typescript
291
- import type { EndpointParams } from '@navios/core'
292
-
293
- import { NotFoundException } from '@navios/core'
294
- import { TestContainer } from '@navios/core/testing'
295
-
296
- import { UserController } from './user.controller'
297
- import { UserService } from './user.service'
298
-
299
- describe('UserController', () => {
300
- let container: TestContainer
301
- let controller: UserController
302
- let userService: vi.Mocked<UserService>
303
-
304
- beforeEach(async () => {
305
- userService = {
306
- findById: vi.fn(),
307
- findAll: vi.fn(),
308
- create: vi.fn(),
309
- update: vi.fn(),
310
- delete: vi.fn(),
311
- } as any
312
-
313
- container = new TestContainer()
314
- // Use dependency injection or manual injection
315
- controller = await container.get(UserController)
316
- // Inject mocked service (implementation depends on your DI setup)
317
- })
318
-
319
- describe('getUserById', () => {
320
- it('should return user when found', async () => {
321
- const mockUser = { id: '1', name: 'John', email: 'john@test.com' }
322
- userService.findById.mockResolvedValue(mockUser)
323
-
324
- const result = await controller.getUserById({
325
- params: { id: '1' },
326
- query: {},
327
- data: {},
328
- headers: {},
329
- request: {} as any,
330
- response: {} as any,
331
- })
332
-
333
- expect(result).toEqual(mockUser)
334
- expect(userService.findById).toHaveBeenCalledWith('1')
335
- })
336
-
337
- it('should throw NotFoundException when user not found', async () => {
338
- userService.findById.mockResolvedValue(null)
339
-
340
- await expect(
341
- controller.getUserById({
342
- params: { id: '1' },
343
- query: {},
344
- data: {},
345
- headers: {},
346
- request: {} as any,
347
- response: {} as any,
348
- }),
349
- ).rejects.toThrow(NotFoundException)
350
- })
351
- })
352
-
353
- describe('createUser', () => {
354
- it('should create and return new user', async () => {
355
- const userData = { name: 'John', email: 'john@test.com' }
356
- const createdUser = { id: '1', ...userData }
357
-
358
- userService.create.mockResolvedValue(createdUser)
359
-
360
- const result = await controller.createUser({
361
- params: {},
362
- query: {},
363
- data: userData,
364
- headers: {},
365
- request: {} as any,
366
- response: {} as any,
367
- })
368
-
369
- expect(result).toEqual(createdUser)
370
- expect(userService.create).toHaveBeenCalledWith(userData)
371
- })
372
- })
373
- })
374
- ```
375
-
376
- ### Testing Guards
377
-
378
- ```typescript
379
- import { TestContainer } from '@navios/core/testing'
380
-
381
- import { AuthGuard } from './auth.guard'
382
- import { JwtService } from './jwt.service'
383
- import { UserService } from './user.service'
384
-
385
- describe('AuthGuard', () => {
386
- let guard: AuthGuard
387
- let jwtService: vi.Mocked<JwtService>
388
- let userService: vi.Mocked<UserService>
389
-
390
- beforeEach(() => {
391
- const container = new TestContainer()
392
-
393
- jwtService = {
394
- verify: vi.fn(),
395
- } as any
396
-
397
- userService = {
398
- findById: vi.fn(),
399
- } as any
400
-
401
- container.bind(JwtService).toValue(jwtService)
402
- container.bind(UserService).toValue(userService)
403
-
404
- guard = container.get(AuthGuard)
405
- })
406
-
407
- describe('canActivate', () => {
408
- it('should return true for valid token', async () => {
409
- const mockUser = { id: '1', isActive: true }
410
- const context = {
411
- headers: { authorization: 'Bearer valid-token' },
412
- request: {},
413
- } as any
414
-
415
- jwtService.verify.mockResolvedValue({ sub: '1' })
416
- userService.findById.mockResolvedValue(mockUser)
417
-
418
- const result = await guard.canActivate(context)
419
-
420
- expect(result).toBe(true)
421
- expect(context.request.user).toEqual(mockUser)
422
- })
423
-
424
- it('should return false for invalid token', async () => {
425
- const context = {
426
- headers: { authorization: 'Bearer invalid-token' },
427
- request: {},
428
- } as any
429
-
430
- jwtService.verify.mockRejectedValue(new Error('Invalid token'))
431
-
432
- const result = await guard.canActivate(context)
433
-
434
- expect(result).toBe(false)
435
- expect(context.request.user).toBeUndefined()
436
- })
437
-
438
- it('should return false when no token provided', async () => {
439
- const context = {
440
- headers: {},
441
- request: {},
442
- } as any
443
-
444
- const result = await guard.canActivate(context)
445
-
446
- expect(result).toBe(false)
447
- })
448
- })
449
- })
450
- ```
451
-
452
- ## Integration Testing
453
-
454
- ### Testing Module Integration
455
-
456
- ```typescript
457
- import { createTestingModule } from '@navios/core/testing'
458
- import { defineFastifyEnvironment } from '@navios/adapter-fastify'
459
-
460
- import { DatabaseService } from './database.service'
461
- import { UserModule } from './user.module'
462
- import { UserService } from './user.service'
463
-
464
- describe('UserModule', () => {
465
- let testingModule: ReturnType<typeof createTestingModule>
466
- let userService: UserService
467
- let databaseService: DatabaseService
468
-
469
- beforeAll(async () => {
470
- testingModule = createTestingModule(UserModule, {
471
- adapter: defineFastifyEnvironment(),
472
- })
473
-
474
- await testingModule.init()
475
-
476
- userService = await testingModule.get(UserService)
477
- databaseService = await testingModule.get(DatabaseService)
478
- })
479
-
480
- afterAll(async () => {
481
- await testingModule.close()
482
- })
483
-
484
- it('should be defined', () => {
485
- expect(userService).toBeDefined()
486
- expect(databaseService).toBeDefined()
487
- })
488
-
489
- it('should inject dependencies correctly', () => {
490
- expect(userService).toBeInstanceOf(UserService)
491
- })
492
- })
493
- ```
494
-
495
- ### Testing HTTP Endpoints
496
-
497
- When testing HTTP endpoints, ensure your endpoints are defined using `@navios/builder` for proper validation and type safety.
498
-
499
- ```typescript
500
- import { defineFastifyEnvironment } from '@navios/adapter-fastify'
501
- import { createTestingModule } from '@navios/core/testing'
502
-
503
- import * as request from 'supertest'
504
-
505
- import { AppModule } from '../app.module'
506
-
507
- describe('UserController (e2e)', () => {
508
- let testingModule: ReturnType<typeof createTestingModule>
509
- let httpServer: any
510
-
511
- beforeAll(async () => {
512
- testingModule = createTestingModule(AppModule, {
513
- adapter: defineFastifyEnvironment(),
514
- })
515
-
516
- const app = await testingModule.init()
517
- httpServer = app.getServer()
518
- })
519
-
520
- afterAll(async () => {
521
- await testingModule.close()
522
- })
523
-
524
- describe('/users (GET)', () => {
525
- it('should return array of users', () => {
526
- return request(httpServer)
527
- .get('/users')
528
- .expect(200)
529
- .expect((res) => {
530
- expect(Array.isArray(res.body)).toBe(true)
531
- })
532
- })
533
- })
534
-
535
- describe('/users/:id (GET)', () => {
536
- it('should return user by id', () => {
537
- return request(httpServer)
538
- .get('/users/1')
539
- .expect(200)
540
- .expect((res) => {
541
- expect(res.body).toHaveProperty('id')
542
- expect(res.body.id).toBe('1')
543
- })
544
- })
545
-
546
- it('should return 404 for non-existent user', () => {
547
- return request(httpServer).get('/users/999').expect(404)
548
- })
549
- })
550
-
551
- describe('/users (POST)', () => {
552
- it('should create new user', () => {
553
- const userData = {
554
- name: 'John Doe',
555
- email: 'john@test.com',
556
- }
557
-
558
- return request(httpServer)
559
- .post('/users')
560
- .send(userData)
561
- .expect(201)
562
- .expect((res) => {
563
- expect(res.body).toHaveProperty('id')
564
- expect(res.body.name).toBe(userData.name)
565
- expect(res.body.email).toBe(userData.email)
566
- })
567
- })
568
-
569
- it('should return 400 for invalid data', () => {
570
- return request(httpServer)
571
- .post('/users')
572
- .send({ name: '' }) // Invalid data
573
- .expect(400)
574
- })
575
- })
576
- })
577
-
578
- describe('/upload (POST) - Multipart', () => {
579
- it('should handle file uploads', () => {
580
- return request(httpServer)
581
- .post('/upload')
582
- .attach('file', Buffer.from('test file content'), 'test.txt')
583
- .field('description', 'Test file upload')
584
- .expect(201)
585
- .expect((res) => {
586
- expect(res.body).toHaveProperty('filename')
587
- expect(res.body).toHaveProperty('size')
588
- })
589
- })
590
- })
591
- })
592
- ```
593
-
594
- ### Testing Multipart Endpoints
595
-
596
- When testing multipart endpoints defined with `@navios/builder`:
597
-
598
- ```typescript
599
- // api/upload.endpoints.ts
600
- import { builder } from '@navios/builder'
601
- // upload.controller.ts
602
- import { Controller, Multipart, MultipartParams } from '@navios/core'
603
-
604
- import { z } from 'zod'
605
-
606
- const api = builder()
607
-
608
- export const uploadEndpoint = api.declareMultipart({
609
- method: 'POST',
610
- url: '/upload',
611
- requestSchema: z.object({
612
- files: z.array(z.instanceof(File)),
613
- description: z.string(),
614
- }),
615
- responseSchema: z.object({
616
- filename: z.string(),
617
- size: z.number(),
618
- }),
619
- })
620
-
621
- @Controller()
622
- export class UploadController {
623
- @Multipart(uploadEndpoint)
624
- async uploadFile(params: MultipartParams<typeof uploadEndpoint>) {
625
- const { files, description } = params.data
626
- // Handle file upload logic
627
- return {
628
- filename: files[0].name,
629
- size: files[0].size,
630
- }
631
- }
632
- }
633
- ```
634
-
635
- ## Testing with Authentication
636
-
637
- ### Testing Protected Endpoints
638
-
639
- ```typescript
640
- describe('Protected Endpoints', () => {
641
- let authToken: string
642
-
643
- beforeAll(async () => {
644
- // Login and get auth token
645
- const loginResponse = await request(httpServer)
646
- .post('/auth/login')
647
- .send({
648
- email: 'test@example.com',
649
- password: 'password',
650
- })
651
- .expect(200)
652
-
653
- authToken = loginResponse.body.token
654
- })
655
-
656
- describe('/profile (GET)', () => {
657
- it('should return user profile with valid token', () => {
658
- return request(httpServer)
659
- .get('/profile')
660
- .set('Authorization', `Bearer ${authToken}`)
661
- .expect(200)
662
- })
663
-
664
- it('should return 401 without token', () => {
665
- return request(httpServer).get('/profile').expect(401)
666
- })
667
-
668
- it('should return 401 with invalid token', () => {
669
- return request(httpServer)
670
- .get('/profile')
671
- .set('Authorization', `Bearer invalid-token`)
672
- .expect(401)
673
- })
674
- })
675
- })
676
- ```
677
-
678
- ## Mock Strategies
679
-
680
- ### Creating Service Mocks
681
-
682
- ```typescript
683
- // test/mocks/user.service.mock.ts
684
- export const mockUserService = {
685
- findById: vi.fn(),
686
- findAll: vi.fn(),
687
- create: vi.fn(),
688
- update: vi.fn(),
689
- delete: vi.fn(),
690
- }
691
-
692
- // Reset mocks between tests
693
- beforeEach(() => {
694
- vi.clearAllMocks()
695
- })
696
- ```
697
-
698
- ### Factory Pattern for Test Data
699
-
700
- ```typescript
701
- // test/factories/user.factory.ts
702
- export class UserFactory {
703
- static create(overrides: Partial<User> = {}): User {
704
- return {
705
- id: '1',
706
- name: 'John Doe',
707
- email: 'john@test.com',
708
- createdAt: new Date(),
709
- updatedAt: new Date(),
710
- ...overrides,
711
- }
712
- }
713
-
714
- static createMany(count: number, overrides: Partial<User> = {}): User[] {
715
- return Array.from({ length: count }, (_, i) =>
716
- this.create({
717
- id: String(i + 1),
718
- ...overrides,
719
- }),
720
- )
721
- }
722
- }
723
-
724
- // Usage in tests
725
- describe('UserService', () => {
726
- it('should handle multiple users', async () => {
727
- const users = UserFactory.createMany(3)
728
- mockDatabase.users.findMany.mockResolvedValue(users)
729
-
730
- const result = await userService.findAll()
731
-
732
- expect(result).toHaveLength(3)
733
- expect(result).toEqual(users)
734
- })
735
- })
736
- ```
737
-
738
- ## Test Organization
739
-
740
- ### Folder Structure
741
-
742
- ```
743
- src/
744
- ├── user/
745
- │ ├── user.controller.ts
746
- │ ├── user.service.ts
747
- │ ├── user.module.ts
748
- │ └── __tests__/
749
- │ ├── user.controller.spec.ts
750
- │ ├── user.service.spec.ts
751
- └── test/
752
- ├── fixtures/
753
- ├── mocks/
754
- ├── factories/
755
- └── e2e/
756
- └── user.e2e-spec.ts
757
- ```
758
-
759
- ## Best Practices
760
-
761
- ### 1. Test Isolation
762
-
763
- Ensure tests don't depend on each other:
764
-
765
- ```typescript
766
- describe('UserService', () => {
767
- beforeEach(() => {
768
- // Reset state before each test
769
- vi.clearAllMocks()
770
- })
771
-
772
- // Each test should be independent
773
- })
774
- ```
775
-
776
- ### 2. Use Descriptive Test Names
777
-
778
- ```typescript
779
- // ✅ Good - Descriptive names
780
- it('should throw NotFoundException when user does not exist', () => {})
781
- it('should return user data when valid ID is provided', () => {})
782
-
783
- // ❌ Avoid - Vague names
784
- it('should work', () => {})
785
- it('should fail', () => {})
786
- ```
787
-
788
- ### 3. Test Edge Cases
789
-
790
- ```typescript
791
- describe('UserService.findById', () => {
792
- it('should return user for valid ID', async () => {
793
- // Happy path
794
- })
795
-
796
- it('should return null for non-existent ID', async () => {
797
- // Edge case
798
- })
799
-
800
- it('should handle database connection errors', async () => {
801
- // Error case
802
- })
803
-
804
- it('should validate ID format', async () => {
805
- // Input validation
806
- })
807
- })
808
- ```
809
-
810
- ### 4. Keep Tests Simple
811
-
812
- ```typescript
813
- // ✅ Good - Simple and focused
814
- it('should create user with valid data', async () => {
815
- const userData = { name: 'John', email: 'john@test.com' }
816
- mockDatabase.users.create.mockResolvedValue({ id: '1', ...userData })
817
-
818
- const result = await userService.create(userData)
819
-
820
- expect(result).toMatchObject(userData)
821
- })
822
-
823
- // ❌ Avoid - Testing multiple things
824
- it('should create user and send email and log event', async () => {
825
- // Too many responsibilities
826
- })
827
- ```