@navios/core 1.1.0 → 2.0.0-alpha.1

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 +85 -13
  2. package/README.md +69 -220
  3. package/lib/async-context-BAdt7bno.d.mts +239 -0
  4. package/lib/async-context-BAdt7bno.d.mts.map +1 -0
  5. package/lib/async-context-RsWmy2Hi.d.cts +239 -0
  6. package/lib/async-context-RsWmy2Hi.d.cts.map +1 -0
  7. package/lib/attribute-factory-BW1kgBqf.d.mts +70 -0
  8. package/lib/attribute-factory-BW1kgBqf.d.mts.map +1 -0
  9. package/lib/attribute-factory-DqN4x5XM.d.cts +70 -0
  10. package/lib/attribute-factory-DqN4x5XM.d.cts.map +1 -0
  11. package/lib/attribute-value-BNiJjxl1.mjs +225 -0
  12. package/lib/attribute-value-BNiJjxl1.mjs.map +1 -0
  13. package/lib/attribute-value-Cux5HhOL.cjs +314 -0
  14. package/lib/attribute-value-Cux5HhOL.cjs.map +1 -0
  15. package/lib/basic-execution-context-5uq2DvEA.cjs +318 -0
  16. package/lib/basic-execution-context-5uq2DvEA.cjs.map +1 -0
  17. package/lib/basic-execution-context-u1VktGoM.mjs +277 -0
  18. package/lib/basic-execution-context-u1VktGoM.mjs.map +1 -0
  19. package/lib/execution-context-BVSmLkYp.d.cts +71 -0
  20. package/lib/execution-context-BVSmLkYp.d.cts.map +1 -0
  21. package/lib/execution-context-C5F9rojO.d.mts +71 -0
  22. package/lib/execution-context-C5F9rojO.d.mts.map +1 -0
  23. package/lib/execution-context-token--cKS4cJv.cjs +270 -0
  24. package/lib/execution-context-token--cKS4cJv.cjs.map +1 -0
  25. package/lib/execution-context-token-Cb3M3Ao0.mjs +223 -0
  26. package/lib/execution-context-token-Cb3M3Ao0.mjs.map +1 -0
  27. package/lib/index.cjs +1672 -4426
  28. package/lib/index.cjs.map +1 -1
  29. package/lib/index.d.cts +842 -3
  30. package/lib/index.d.cts.map +1 -0
  31. package/lib/index.d.mts +842 -3
  32. package/lib/index.d.mts.map +1 -0
  33. package/lib/index.mjs +1559 -4221
  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-Bz83ZnJ5.cjs +173 -0
  44. package/lib/module-Bz83ZnJ5.cjs.map +1 -0
  45. package/lib/module-options-CSqQUSTm.d.mts +51 -0
  46. package/lib/module-options-CSqQUSTm.d.mts.map +1 -0
  47. package/lib/module-options-DSRBri4J.d.cts +51 -0
  48. package/lib/module-options-DSRBri4J.d.cts.map +1 -0
  49. package/lib/module-zPXwR2qp.mjs +138 -0
  50. package/lib/module-zPXwR2qp.mjs.map +1 -0
  51. package/lib/settled-within-B6gpu2XW.cjs +32 -0
  52. package/lib/settled-within-B6gpu2XW.cjs.map +1 -0
  53. package/lib/settled-within-Bc2pj8WB.mjs +21 -0
  54. package/lib/settled-within-Bc2pj8WB.mjs.map +1 -0
  55. package/lib/testing/index.cjs +74 -414
  56. package/lib/testing/index.cjs.map +1 -1
  57. package/lib/testing/index.d.cts +25 -385
  58. package/lib/testing/index.d.cts.map +1 -1
  59. package/lib/testing/index.d.mts +24 -385
  60. package/lib/testing/index.d.mts.map +1 -1
  61. package/lib/testing/index.mjs +72 -408
  62. package/lib/testing/index.mjs.map +1 -1
  63. package/lib/transport.cjs +36 -0
  64. package/lib/transport.d.cts +254 -0
  65. package/lib/transport.d.cts.map +1 -0
  66. package/lib/transport.d.mts +254 -0
  67. package/lib/transport.d.mts.map +1 -0
  68. package/lib/transport.mjs +6 -0
  69. package/package.json +37 -17
  70. package/docs/README.md +0 -316
  71. package/docs/adapters.md +0 -308
  72. package/docs/application-setup.md +0 -524
  73. package/docs/attributes.md +0 -689
  74. package/docs/controllers.md +0 -373
  75. package/docs/endpoints.md +0 -444
  76. package/docs/exceptions.md +0 -352
  77. package/docs/guards.md +0 -550
  78. package/docs/legacy-compat.md +0 -356
  79. package/docs/modules.md +0 -377
  80. package/docs/quick-start.md +0 -290
  81. package/docs/services.md +0 -427
  82. package/docs/testing.md +0 -827
  83. package/lib/index-3LcTrbxz.d.mts +0 -3804
  84. package/lib/index-3LcTrbxz.d.mts.map +0 -1
  85. package/lib/index-B14SekVb.d.cts +0 -3804
  86. package/lib/index-B14SekVb.d.cts.map +0 -1
  87. package/lib/navios.factory-CUrO_p6K.cjs +0 -4538
  88. package/lib/navios.factory-CUrO_p6K.cjs.map +0 -1
  89. package/lib/navios.factory-DjUOOVVL.mjs +0 -4151
  90. package/lib/navios.factory-DjUOOVVL.mjs.map +0 -1
  91. package/lib/tokens-BEuBMGGX.cjs +0 -193
  92. package/lib/tokens-BEuBMGGX.cjs.map +0 -1
  93. package/lib/tokens-COyNGV1I.mjs +0 -97
  94. package/lib/tokens-COyNGV1I.mjs.map +0 -1
  95. package/lib/use-guards.decorator-DLmRl2CV.mjs +0 -336
  96. package/lib/use-guards.decorator-DLmRl2CV.mjs.map +0 -1
  97. package/lib/use-guards.decorator-DhumFTk3.cjs +0 -444
  98. package/lib/use-guards.decorator-DhumFTk3.cjs.map +0 -1
  99. package/project.json +0 -66
  100. package/src/__tests__/attribute.factory.spec.mts +0 -300
  101. package/src/__tests__/config.service.spec.mts +0 -43
  102. package/src/__tests__/console-logger.service.spec.mts +0 -312
  103. package/src/__tests__/controller-resolver.spec.mts +0 -229
  104. package/src/__tests__/controller.spec.mts +0 -58
  105. package/src/__tests__/guard-runner.service.spec.mts +0 -399
  106. package/src/__tests__/logger.service.spec.mts +0 -147
  107. package/src/__tests__/responders.spec.mts +0 -340
  108. package/src/__tests__/testing-module.spec.mts +0 -459
  109. package/src/__tests__/unit-testing-module.spec.mts +0 -424
  110. package/src/attribute.factory.mts +0 -325
  111. package/src/config/config-service.interface.mts +0 -47
  112. package/src/config/config.provider.mts +0 -69
  113. package/src/config/config.service.mts +0 -176
  114. package/src/config/index.mts +0 -5
  115. package/src/config/types.mts +0 -58
  116. package/src/config/utils/helpers.mts +0 -23
  117. package/src/config/utils/index.mts +0 -1
  118. package/src/decorators/controller.decorator.mts +0 -81
  119. package/src/decorators/endpoint.decorator.mts +0 -181
  120. package/src/decorators/header.decorator.mts +0 -38
  121. package/src/decorators/http-code.decorator.mts +0 -38
  122. package/src/decorators/index.mts +0 -8
  123. package/src/decorators/module.decorator.mts +0 -106
  124. package/src/decorators/multipart.decorator.mts +0 -169
  125. package/src/decorators/stream.decorator.mts +0 -155
  126. package/src/decorators/use-guards.decorator.mts +0 -73
  127. package/src/exceptions/bad-request.exception.mts +0 -28
  128. package/src/exceptions/conflict.exception.mts +0 -31
  129. package/src/exceptions/forbidden.exception.mts +0 -30
  130. package/src/exceptions/http.exception.mts +0 -33
  131. package/src/exceptions/index.mts +0 -7
  132. package/src/exceptions/internal-server-error.exception.mts +0 -33
  133. package/src/exceptions/not-found.exception.mts +0 -33
  134. package/src/exceptions/unauthorized.exception.mts +0 -30
  135. package/src/factories/adapter.factory.mts +0 -20
  136. package/src/factories/endpoint-adapter.factory.mts +0 -21
  137. package/src/factories/http-adapter.factory.mts +0 -20
  138. package/src/factories/index.mts +0 -8
  139. package/src/factories/multipart-adapter.factory.mts +0 -21
  140. package/src/factories/reply.factory.mts +0 -21
  141. package/src/factories/request.factory.mts +0 -21
  142. package/src/factories/stream-adapter.factory.mts +0 -20
  143. package/src/factories/xml-stream-adapter.factory.mts +0 -20
  144. package/src/index.mts +0 -16
  145. package/src/interfaces/abstract-adapter.interface.mts +0 -32
  146. package/src/interfaces/abstract-execution-context.inteface.mts +0 -48
  147. package/src/interfaces/abstract-http-adapter.interface.mts +0 -79
  148. package/src/interfaces/abstract-http-cors-options.interface.mts +0 -59
  149. package/src/interfaces/abstract-http-handler-adapter.interface.mts +0 -127
  150. package/src/interfaces/abstract-http-listen-options.interface.mts +0 -4
  151. package/src/interfaces/adapter-environment.interface.mts +0 -74
  152. package/src/interfaces/can-activate.mts +0 -38
  153. package/src/interfaces/http-header.mts +0 -18
  154. package/src/interfaces/index.mts +0 -14
  155. package/src/interfaces/navios-module.mts +0 -28
  156. package/src/interfaces/plugin-context.mts +0 -104
  157. package/src/interfaces/plugin-stage.mts +0 -62
  158. package/src/interfaces/plugin.interface.mts +0 -119
  159. package/src/interfaces/staged-plugin.interface.mts +0 -209
  160. package/src/legacy-compat/__type-tests__/legacy-decorators.spec-d.mts +0 -521
  161. package/src/legacy-compat/__type-tests__/tsconfig.json +0 -15
  162. package/src/legacy-compat/attribute.factory.mts +0 -351
  163. package/src/legacy-compat/decorators/controller.decorator.mts +0 -31
  164. package/src/legacy-compat/decorators/endpoint.decorator.mts +0 -73
  165. package/src/legacy-compat/decorators/header.decorator.mts +0 -43
  166. package/src/legacy-compat/decorators/http-code.decorator.mts +0 -39
  167. package/src/legacy-compat/decorators/index.mts +0 -11
  168. package/src/legacy-compat/decorators/module.decorator.mts +0 -37
  169. package/src/legacy-compat/decorators/multipart.decorator.mts +0 -72
  170. package/src/legacy-compat/decorators/stream.decorator.mts +0 -89
  171. package/src/legacy-compat/decorators/use-guards.decorator.mts +0 -80
  172. package/src/legacy-compat/index.mts +0 -57
  173. package/src/logger/README.md +0 -3
  174. package/src/logger/console-logger.service.mts +0 -714
  175. package/src/logger/index.mts +0 -6
  176. package/src/logger/log-levels.mts +0 -21
  177. package/src/logger/logger-service.interface.mts +0 -42
  178. package/src/logger/logger.service.mts +0 -113
  179. package/src/logger/logger.tokens.mts +0 -44
  180. package/src/logger/utils/cli-colors.util.mts +0 -17
  181. package/src/logger/utils/filter-log-levelts.util.mts +0 -29
  182. package/src/logger/utils/index.mts +0 -5
  183. package/src/logger/utils/is-log-level-enabled.mts +0 -33
  184. package/src/logger/utils/is-log-level.util.mts +0 -10
  185. package/src/logger/utils/shared.utils.mts +0 -51
  186. package/src/metadata/controller.metadata.mts +0 -79
  187. package/src/metadata/handler.metadata.mts +0 -80
  188. package/src/metadata/index.mts +0 -4
  189. package/src/metadata/module.metadata.mts +0 -116
  190. package/src/metadata/navios-managed.metadata.mts +0 -42
  191. package/src/navios.application.mts +0 -678
  192. package/src/navios.environment.mts +0 -42
  193. package/src/navios.factory.mts +0 -158
  194. package/src/responders/enums/framework-error.enum.mts +0 -38
  195. package/src/responders/enums/index.mts +0 -1
  196. package/src/responders/index.mts +0 -4
  197. package/src/responders/interfaces/error-responder.interface.mts +0 -42
  198. package/src/responders/interfaces/error-response.interface.mts +0 -22
  199. package/src/responders/interfaces/index.mts +0 -3
  200. package/src/responders/interfaces/problem-details.interface.mts +0 -34
  201. package/src/responders/services/error-response-producer.service.mts +0 -143
  202. package/src/responders/services/forbidden-responder.service.mts +0 -77
  203. package/src/responders/services/index.mts +0 -5
  204. package/src/responders/services/internal-server-error-responder.service.mts +0 -57
  205. package/src/responders/services/not-found-responder.service.mts +0 -76
  206. package/src/responders/services/validation-error-responder.service.mts +0 -78
  207. package/src/responders/tokens/index.mts +0 -1
  208. package/src/responders/tokens/responder.tokens.mts +0 -84
  209. package/src/services/abstract-handler-adapter.service.mts +0 -366
  210. package/src/services/guard-runner.service.mts +0 -152
  211. package/src/services/index.mts +0 -4
  212. package/src/services/instance-resolver.service.mts +0 -177
  213. package/src/services/module-loader.service.mts +0 -255
  214. package/src/stores/index.mts +0 -1
  215. package/src/stores/request-id.store.mts +0 -85
  216. package/src/testing/index.mts +0 -3
  217. package/src/testing/testing-module.mts +0 -393
  218. package/src/testing/unit-testing-module.mts +0 -298
  219. package/src/tokens/adapter.token.mts +0 -6
  220. package/src/tokens/endpoint-adapter.token.mts +0 -8
  221. package/src/tokens/execution-context.token.mts +0 -9
  222. package/src/tokens/http-adapter.token.mts +0 -8
  223. package/src/tokens/index.mts +0 -10
  224. package/src/tokens/multipart-adapter.token.mts +0 -8
  225. package/src/tokens/navios-options.token.mts +0 -6
  226. package/src/tokens/reply.token.mts +0 -3
  227. package/src/tokens/request.token.mts +0 -3
  228. package/src/tokens/stream-adapter.token.mts +0 -8
  229. package/src/tokens/xml-stream-adapter.token.mts +0 -8
  230. package/src/utils/adapter-supports.util.mts +0 -47
  231. package/src/utils/define-plugin.mts +0 -251
  232. package/src/utils/index.mts +0 -2
  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
- ```