@forinda/kickjs-testing 3.2.0 → 4.1.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.
package/README.md CHANGED
@@ -1,37 +1,27 @@
1
1
  # @forinda/kickjs-testing
2
2
 
3
- Test utilities for KickJS — `createTestApp` and `createTestModule` helpers.
3
+ Test utilities for KickJS — `createTestApp`, `createTestModule`, `runContributor` (single contributor in isolation), and `createTestPlugin` (plugin harness with isolated container + lifecycle invokers).
4
4
 
5
5
  ## Install
6
6
 
7
7
  ```bash
8
- # Using the KickJS CLI (recommended — installs as dev dependency)
9
- kick add testing
10
-
11
- # Manual install
12
8
  pnpm add -D @forinda/kickjs-testing
13
9
  ```
14
10
 
15
- ## Features
16
-
17
- - `createTestApp()` — creates an Application instance for testing (resets container, empty middleware)
18
- - `createTestModule()` — builds a dynamic test module with custom DI registrations
19
- - DI overrides for mocking repositories and services (supports symbol keys)
20
-
21
11
  ## Quick Example
22
12
 
23
- ```typescript
24
- import { createTestApp } from '@forinda/kickjs-testing'
13
+ ```ts
25
14
  import { describe, it, expect } from 'vitest'
26
15
  import supertest from 'supertest'
16
+ import { createTestApp } from '@forinda/kickjs-testing'
17
+ import { UserModule, USER_REPO } from './modules/users'
18
+ import { MockUserRepository } from './mocks'
27
19
 
28
20
  describe('UserController', () => {
29
21
  it('lists users', async () => {
30
- const { expressApp } = createTestApp({
22
+ const { expressApp } = await createTestApp({
31
23
  modules: [UserModule],
32
- overrides: {
33
- [USER_REPO]: new MockUserRepository(),
34
- },
24
+ overrides: { [USER_REPO]: new MockUserRepository() },
35
25
  })
36
26
 
37
27
  const res = await supertest(expressApp).get('/api/v1/users')
@@ -42,7 +32,7 @@ describe('UserController', () => {
42
32
 
43
33
  ## Documentation
44
34
 
45
- [Full documentation](https://github.com/forinda/kick-js)
35
+ [forinda.github.io/kick-js/guide/testing](https://forinda.github.io/kick-js/guide/testing)
46
36
 
47
37
  ## License
48
38
 
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
2
  import express from "express";
3
- import { AppAdapter, AppModuleClass, Application, ApplicationOptions, Container, ContextDecorator, ExecutionContext, MetaValue, ModuleRoutes } from "@forinda/kickjs";
3
+ import { AppAdapter, AppModuleClass, Application, ApplicationOptions, Container, ContextDecorator, ContributorRegistration, ExecutionContext, KickPlugin, MetaValue, ModuleRoutes } from "@forinda/kickjs";
4
4
 
5
5
  //#region src/index.d.ts
6
6
  /**
@@ -130,6 +130,104 @@ interface RunContributorResult<K extends string> {
130
130
  * ```
131
131
  */
132
132
  declare function runContributor<K extends string, D extends Record<string, any> = Record<string, never>>(decorator: ContextDecorator<K, D, ExecutionContext>, options?: RunContributorOptions): Promise<RunContributorResult<K>>;
133
+ /**
134
+ * Options for {@link createTestPlugin}.
135
+ */
136
+ interface CreateTestPluginOptions {
137
+ /**
138
+ * Use an isolated container (default: `true`). Isolated harnesses never
139
+ * touch the global `Container.getInstance()` singleton, so concurrent
140
+ * tests can run without stomping each other's DI state.
141
+ */
142
+ isolated?: boolean;
143
+ /**
144
+ * Skip auto-invoking `plugin.register(container)` — useful when a test
145
+ * wants to assert container state *before* the plugin touches it.
146
+ * Defaults to `false` (register is called eagerly).
147
+ */
148
+ skipRegister?: boolean;
149
+ }
150
+ /**
151
+ * Result of {@link createTestPlugin}. Mirrors the spec sketch in
152
+ * `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a
153
+ * `runContributors()` helper that builds a one-plugin pipeline against a
154
+ * fake `ExecutionContext`.
155
+ */
156
+ interface PluginTestHarness {
157
+ /** The plugin under test — exposed for direct introspection. */
158
+ readonly plugin: KickPlugin;
159
+ /** Isolated (or shared) DI container the plugin registered into. */
160
+ readonly container: Container;
161
+ /**
162
+ * Invoke `plugin.onReady(container)`. No-op if the plugin does not
163
+ * define the hook.
164
+ */
165
+ callOnReady(): Promise<void>;
166
+ /**
167
+ * Invoke `plugin.shutdown()`. No-op if the plugin does not define the
168
+ * hook.
169
+ */
170
+ shutdown(): Promise<void>;
171
+ /**
172
+ * Returns the module classes the plugin ships via `plugin.modules?()`.
173
+ * The harness does **not** auto-instantiate them — use `createTestApp`
174
+ * for that. Useful for assertions like "the plugin exposes the module I
175
+ * expect".
176
+ */
177
+ modules(): AppModuleClass[];
178
+ /**
179
+ * Returns adapter instances the plugin ships via `plugin.adapters?()`.
180
+ * Useful for testing the adapters alongside the plugin's DI bindings.
181
+ */
182
+ adapters(): AppAdapter[];
183
+ /**
184
+ * Returns middleware entries the plugin ships via `plugin.middleware?()`.
185
+ */
186
+ middleware(): any[];
187
+ /**
188
+ * Returns contributor registrations the plugin ships via
189
+ * `plugin.contributors?()`.
190
+ */
191
+ contributors(): ContributorRegistration[];
192
+ /**
193
+ * Build a fake {@link ExecutionContext} pre-populated with the given
194
+ * metadata. Symmetric with {@link runContributor}'s fake context.
195
+ */
196
+ makeContext(initial?: Record<string, unknown>): ExecutionContext;
197
+ /**
198
+ * Run every contributor the plugin ships through a built pipeline
199
+ * against the given context. Dependencies resolve through the harness's
200
+ * container (same path production uses). Throws if the plugin's
201
+ * contributors reference `dependsOn` keys no one in the plugin provides.
202
+ */
203
+ runContributors(ctx: ExecutionContext): Promise<void>;
204
+ }
205
+ /**
206
+ * Build an isolated test harness around a single {@link KickPlugin}.
207
+ * Skips the full HTTP layer — symmetric with {@link runContributor} for
208
+ * contributors and {@link createTestApp} for integration runs.
209
+ *
210
+ * @example
211
+ * ```ts
212
+ * const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))
213
+ *
214
+ * // The plugin's register() already ran — resolve any bindings.
215
+ * const flags = harness.container.resolve(FLAGS_SERVICE)
216
+ *
217
+ * // Drive the post-bootstrap lifecycle.
218
+ * await harness.callOnReady()
219
+ *
220
+ * // Exercise contributors shipped by the plugin.
221
+ * const ctx = harness.makeContext({ requestId: 'req-1' })
222
+ * await harness.runContributors(ctx)
223
+ * expect(ctx.get('flags')).toEqual({ beta: true })
224
+ *
225
+ * await harness.shutdown()
226
+ * ```
227
+ */
228
+ declare function createTestPlugin(plugin: KickPlugin, options?: CreateTestPluginOptions): Promise<PluginTestHarness>;
229
+ /** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */
230
+ declare const testPlugin: typeof createTestPlugin;
133
231
  //#endregion
134
- export { CreateTestAppOptions, RunContributorOptions, RunContributorResult, createTestApp, createTestModule, runContributor };
232
+ export { CreateTestAppOptions, CreateTestPluginOptions, PluginTestHarness, RunContributorOptions, RunContributorResult, createTestApp, createTestModule, createTestPlugin, runContributor, testPlugin };
135
233
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;AAYwB;;KAMnB,2BAAA,GAA8B,IAAA,CACjC,kBAAA;;;AAmBF;;UAAiB,oBAAA,SAA6B,2BAAA;EAC5C,OAAA,EAAS,cAAA;EAEE;EAAX,QAAA,GAAW,UAAA;EAHiC;EAK5C,SAAA,GAAY,MAAA;EAL2D;;;;;EAWvE,QAAA;AAAA;;;;;AAiBF;;;;;;;;;;iBAAsB,aAAA,CAAc,OAAA,EAAS,oBAAA,GAAuB,OAAA;EAClE,GAAA,EAAK,WAAA;EACL,UAAA,EAAY,OAAA,CAAQ,OAAA;EACpB,SAAA,EAAW,SAAA;AAAA;;;;;;;;AA4Eb;;;;;;;;iBAAgB,gBAAA,CAAiB,MAAA;EAC/B,QAAA,GAAW,SAAA,EAAW,SAAA;EACtB,MAAA,QAAc,YAAA,GAAe,YAAA;AAAA,IAC3B,cAAA;;;;UAiBa,qBAAA;EAjBb;;;AAiBJ;;;;;EASE,IAAA,GAAO,MAAA;EAQP;;;;;AASF;EATE,OAAA,GAAU,MAAA;EASyB;EANnC,SAAA;AAAA;;;;UAMe,oBAAA;EAAqB;EAEpC,KAAA,EAAO,SAAA,CAAU,CAAA;EAAV;EAEP,GAAA,EAAK,gBAAA;EAAL;;;;;EAMA,IAAA,EAAM,GAAA;AAAA;;;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ACR,OAAA,CAAQ,oBAAA,CAAqB,CAAA;;AAuBhC;;UAAiB,uBAAA;EAMf;;AAgBF;;;EAhBE,QAAA;EAoBoB;;;;;EAbpB,YAAA;AAAA;;;;;;;UASe,iBAAA;EAIN;EAAA,SAFA,MAAA,EAAQ,UAAA;EAQjB;EAAA,SANS,SAAA,EAAW,SAAA;EAYpB;;;;EANA,WAAA,IAAe,OAAA;EAoBH;;;;EAdZ,QAAA,IAAY,OAAA;EA+BU;;;;;;EAvBtB,OAAA,IAAW,cAAA;EA+BoC;;AA0BjD;;EAnDE,QAAA,IAAY,UAAA;EAoDJ;;;EA/CR,UAAA;EAiDQ;;;;EA3CR,YAAA,IAAgB,uBAAA;EA0ChB;;;;EApCA,WAAA,CAAY,OAAA,GAAU,MAAA,oBAA0B,gBAAA;EAoGrC;;;;;;EA5FX,eAAA,CAAgB,GAAA,EAAK,gBAAA,GAAmB,OAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;iBA0BpB,gBAAA,CACpB,MAAA,EAAQ,UAAA,EACR,OAAA,GAAS,uBAAA,GACR,OAAA,CAAQ,iBAAA;;cA+DE,UAAA,SAAU,gBAAA"}
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @forinda/kickjs-testing v3.2.0
2
+ * @forinda/kickjs-testing v4.1.0
3
3
  *
4
4
  * Copyright (c) Felix Orinda
5
5
  *
@@ -9,7 +9,7 @@
9
9
  * @license MIT
10
10
  */
11
11
  import express from "express";
12
- import { Application, Container } from "@forinda/kickjs";
12
+ import { Application, Container, buildPipeline, runContributors } from "@forinda/kickjs";
13
13
  //#region src/index.ts
14
14
  /**
15
15
  * Create an Application instance configured for testing.
@@ -133,7 +133,81 @@ async function runContributor(decorator, options = {}) {
133
133
  meta
134
134
  };
135
135
  }
136
+ /**
137
+ * Build an isolated test harness around a single {@link KickPlugin}.
138
+ * Skips the full HTTP layer — symmetric with {@link runContributor} for
139
+ * contributors and {@link createTestApp} for integration runs.
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))
144
+ *
145
+ * // The plugin's register() already ran — resolve any bindings.
146
+ * const flags = harness.container.resolve(FLAGS_SERVICE)
147
+ *
148
+ * // Drive the post-bootstrap lifecycle.
149
+ * await harness.callOnReady()
150
+ *
151
+ * // Exercise contributors shipped by the plugin.
152
+ * const ctx = harness.makeContext({ requestId: 'req-1' })
153
+ * await harness.runContributors(ctx)
154
+ * expect(ctx.get('flags')).toEqual({ beta: true })
155
+ *
156
+ * await harness.shutdown()
157
+ * ```
158
+ */
159
+ async function createTestPlugin(plugin, options = {}) {
160
+ const container = options.isolated ?? true ? Container.create() : (Container.reset(), Container.getInstance());
161
+ if (!options.skipRegister) plugin.register?.(container);
162
+ return {
163
+ plugin,
164
+ container,
165
+ async callOnReady() {
166
+ await plugin.onReady?.(container);
167
+ },
168
+ async shutdown() {
169
+ await plugin.shutdown?.();
170
+ },
171
+ modules() {
172
+ return plugin.modules?.() ?? [];
173
+ },
174
+ adapters() {
175
+ return plugin.adapters?.() ?? [];
176
+ },
177
+ middleware() {
178
+ return plugin.middleware?.() ?? [];
179
+ },
180
+ contributors() {
181
+ return [...plugin.contributors?.() ?? []];
182
+ },
183
+ makeContext(initial = {}) {
184
+ const meta = new Map(Object.entries(initial));
185
+ return {
186
+ get(key) {
187
+ return meta.get(key);
188
+ },
189
+ set(key, value) {
190
+ meta.set(key, value);
191
+ },
192
+ requestId: "test-req"
193
+ };
194
+ },
195
+ async runContributors(ctx) {
196
+ await runContributors({
197
+ pipeline: buildPipeline([...plugin.contributors?.() ?? []].map((registration) => ({
198
+ registration,
199
+ source: "adapter",
200
+ label: plugin.name
201
+ }))),
202
+ ctx,
203
+ container
204
+ });
205
+ }
206
+ };
207
+ }
208
+ /** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */
209
+ const testPlugin = createTestPlugin;
136
210
  //#endregion
137
- export { createTestApp, createTestModule, runContributor };
211
+ export { createTestApp, createTestModule, createTestPlugin, runContributor, testPlugin };
138
212
 
139
213
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import express from 'express'\nimport {\n Application,\n Container,\n type AppAdapter,\n type AppModule,\n type AppModuleClass,\n type ApplicationOptions,\n type ContextDecorator,\n type ExecutionContext,\n type MetaValue,\n type ModuleRoutes,\n} from '@forinda/kickjs'\n\n/**\n * Bootstrap options forwarded verbatim to the underlying Application so\n * test apps exercise the same HTTP pipeline shape as production.\n */\ntype BootstrapPassthroughOptions = Pick<\n ApplicationOptions,\n | 'port'\n | 'apiPrefix'\n | 'defaultVersion'\n | 'middleware'\n | 'onError'\n | 'onNotFound'\n | 'plugins'\n | 'trustProxy'\n | 'jsonLimit'\n | 'security'\n | 'contributors'\n | 'contextStore'\n>\n\n/**\n * Options for creating a test application.\n * Disables helmet, cors, compression, and morgan by default.\n */\nexport interface CreateTestAppOptions extends BootstrapPassthroughOptions {\n modules: AppModuleClass[]\n /** Adapters to attach (auth, queue, devtools, etc.) */\n adapters?: AppAdapter[]\n /** DI overrides applied after module registration. Supports both string and symbol keys. */\n overrides?: Record<symbol | string, any>\n /**\n * Use an isolated container instead of the global singleton.\n * Prevents concurrent tests from interfering with each other's DI state.\n * When true, Container.create() is used instead of Container.reset() + getInstance().\n */\n isolated?: boolean\n}\n\n/**\n * Create an Application instance configured for testing.\n * Resets the DI container, registers modules, applies overrides,\n * and returns both the Application and its Express app.\n *\n * @example\n * ```ts\n * const { expressApp, container } = await createTestApp({\n * modules: [UserModule],\n * overrides: { [USER_REPO]: new InMemoryUserRepo() },\n * })\n * const res = await request(expressApp).get('/api/v1/users')\n * ```\n */\nexport async function createTestApp(options: CreateTestAppOptions): Promise<{\n app: Application\n expressApp: express.Express\n container: Container\n}> {\n let container: Container\n if (options.isolated) {\n // Isolated container — safe for concurrent tests\n container = Container.create()\n } else {\n // Global singleton — reset for serial test isolation (default)\n Container.reset()\n container = Container.getInstance()\n }\n\n const app = new Application({\n modules: options.modules,\n adapters: options.adapters,\n port: options.port,\n apiPrefix: options.apiPrefix,\n defaultVersion: options.defaultVersion,\n // Use provided middleware, or default to JSON body parsing only\n middleware: options.middleware ?? [express.json()],\n onError: options.onError,\n onNotFound: options.onNotFound,\n plugins: options.plugins,\n trustProxy: options.trustProxy,\n jsonLimit: options.jsonLimit,\n security: options.security,\n contributors: options.contributors,\n contextStore: options.contextStore,\n })\n\n // Run setup — mounts routes, registers modules, initializes adapters.\n // Awaited to support future async adapter hooks.\n await Promise.resolve(app.setup())\n\n // When using an isolated container, Application.setup() registers modules\n // on the global singleton (Container.getInstance()). Re-register them on\n // the isolated container so that bindings are available there too.\n if (options.isolated) {\n for (const ModuleClass of options.modules) {\n const mod = new ModuleClass()\n // register() is optional — see AppModule docs\n mod.register?.(container)\n }\n container.bootstrap()\n }\n\n // Apply DI overrides AFTER setup so they take precedence over\n // bindings registered by modules during register().\n if (options.overrides) {\n for (const token of Reflect.ownKeys(options.overrides)) {\n container.registerInstance(token, options.overrides[token as any])\n }\n }\n\n return {\n app,\n expressApp: app.getExpressApp(),\n container,\n }\n}\n\n/**\n * Build a quick TestModule that explicitly registers dependencies.\n * Useful for integration tests that need to control the DI graph.\n *\n * @example\n * ```ts\n * const TestModule = createTestModule({\n * register: (c) => {\n * c.registerFactory(USER_REPO, () => new InMemoryUserRepo())\n * c.register(UserController)\n * },\n * routes: () => buildRoutes(UserController, '/users'),\n * })\n * ```\n */\nexport function createTestModule(config: {\n register: (container: Container) => void\n routes: () => ModuleRoutes | ModuleRoutes[] | null\n}): AppModuleClass {\n class TestModule implements AppModule {\n register(container: Container) {\n config.register(container)\n }\n routes() {\n return config.routes()\n }\n }\n return TestModule\n}\n\n// ── Context Contributor unit-test helper (#107) ─────────────────────────\n\n/**\n * Options for {@link runContributor}.\n */\nexport interface RunContributorOptions {\n /**\n * Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container\n * entirely — bypass for unit tests that want to assert pure resolve()\n * behaviour without standing up a container.\n *\n * Property names must match the spec's `deps` keys; values can be real\n * service instances, mocks, or test doubles.\n */\n deps?: Record<string, unknown>\n\n /**\n * Pre-populate the fake context's metadata Map. Useful for testing\n * contributors with `dependsOn` without running the full pipeline:\n * pre-populate the dependency keys, then assert that `resolve()` reads\n * them and produces the expected output.\n */\n initial?: Record<string, unknown>\n\n /** Override the fake context's `requestId` (default: `'test-req'`). */\n requestId?: string\n}\n\n/**\n * Result of {@link runContributor}.\n */\nexport interface RunContributorResult<K extends string> {\n /** Value returned by the contributor's `resolve()` call. */\n value: MetaValue<K>\n /** The fake `ExecutionContext` used during the run. */\n ctx: ExecutionContext\n /**\n * Final state of the fake context's metadata Map after `resolve()`.\n * Includes any `ctx.set(...)` calls the resolver made plus the final\n * resolved value under the contributor's own key.\n */\n meta: Map<string, unknown>\n}\n\n/**\n * Run a single context contributor in isolation against a fake\n * {@link ExecutionContext}. Skips the container, the topo-sort, and the\n * §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`\n * directly so unit tests can assert pure resolve behaviour.\n *\n * Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`\n * or `await expect(...).rejects.toThrow()` against them. To exercise the\n * full error matrix (optional skip, onError replacement, etc.), build a\n * one-element pipeline with `buildPipeline()` and use `runContributors()`\n * directly.\n *\n * @example\n * ```ts\n * const LoadProject = defineContextDecorator({\n * key: 'project',\n * dependsOn: ['tenant'],\n * deps: { repo: ProjectRepo },\n * resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),\n * })\n *\n * const { value } = await runContributor(LoadProject, {\n * initial: { tenant: { id: 't-1' } },\n * deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },\n * })\n * expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })\n * ```\n */\nexport async function runContributor<\n K extends string,\n D extends Record<string, any> = Record<string, never>,\n>(\n decorator: ContextDecorator<K, D, ExecutionContext>,\n options: RunContributorOptions = {},\n): Promise<RunContributorResult<K>> {\n const meta = new Map<string, unknown>(Object.entries(options.initial ?? {}))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: options.requestId ?? 'test-req',\n }\n\n const value = await decorator.registration.resolve(ctx, (options.deps ?? {}) as never)\n meta.set(decorator.registration.key, value)\n\n return { value: value as MetaValue<K>, ctx, meta }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,eAAsB,cAAc,SAIjC;CACD,IAAI;AACJ,KAAI,QAAQ,SAEV,aAAY,UAAU,QAAQ;MACzB;AAEL,YAAU,OAAO;AACjB,cAAY,UAAU,aAAa;;CAGrC,MAAM,MAAM,IAAI,YAAY;EAC1B,SAAS,QAAQ;EACjB,UAAU,QAAQ;EAClB,MAAM,QAAQ;EACd,WAAW,QAAQ;EACnB,gBAAgB,QAAQ;EAExB,YAAY,QAAQ,cAAc,CAAC,QAAQ,MAAM,CAAC;EAClD,SAAS,QAAQ;EACjB,YAAY,QAAQ;EACpB,SAAS,QAAQ;EACjB,YAAY,QAAQ;EACpB,WAAW,QAAQ;EACnB,UAAU,QAAQ;EAClB,cAAc,QAAQ;EACtB,cAAc,QAAQ;EACvB,CAAC;AAIF,OAAM,QAAQ,QAAQ,IAAI,OAAO,CAAC;AAKlC,KAAI,QAAQ,UAAU;AACpB,OAAK,MAAM,eAAe,QAAQ,QACpB,KAAI,aAAa,CAEzB,WAAW,UAAU;AAE3B,YAAU,WAAW;;AAKvB,KAAI,QAAQ,UACV,MAAK,MAAM,SAAS,QAAQ,QAAQ,QAAQ,UAAU,CACpD,WAAU,iBAAiB,OAAO,QAAQ,UAAU,OAAc;AAItE,QAAO;EACL;EACA,YAAY,IAAI,eAAe;EAC/B;EACD;;;;;;;;;;;;;;;;;AAkBH,SAAgB,iBAAiB,QAGd;CACjB,MAAM,WAAgC;EACpC,SAAS,WAAsB;AAC7B,UAAO,SAAS,UAAU;;EAE5B,SAAS;AACP,UAAO,OAAO,QAAQ;;;AAG1B,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2ET,eAAsB,eAIpB,WACA,UAAiC,EAAE,EACD;CAClC,MAAM,OAAO,IAAI,IAAqB,OAAO,QAAQ,QAAQ,WAAW,EAAE,CAAC,CAAC;CAC5E,MAAM,MAAwB;EAC5B,IAAI,KAAK;AACP,UAAO,KAAK,IAAI,IAAI;;EAEtB,IAAI,KAAK,OAAO;AACd,QAAK,IAAI,KAAK,MAAM;;EAEtB,WAAW,QAAQ,aAAa;EACjC;CAED,MAAM,QAAQ,MAAM,UAAU,aAAa,QAAQ,KAAM,QAAQ,QAAQ,EAAE,CAAW;AACtF,MAAK,IAAI,UAAU,aAAa,KAAK,MAAM;AAE3C,QAAO;EAAS;EAAuB;EAAK;EAAM"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import express from 'express'\nimport {\n Application,\n Container,\n buildPipeline,\n runContributors,\n type AppAdapter,\n type AppModule,\n type AppModuleClass,\n type ApplicationOptions,\n type ContextDecorator,\n type ContributorRegistration,\n type ExecutionContext,\n type KickPlugin,\n type MetaValue,\n type ModuleRoutes,\n} from '@forinda/kickjs'\n\n/**\n * Bootstrap options forwarded verbatim to the underlying Application so\n * test apps exercise the same HTTP pipeline shape as production.\n */\ntype BootstrapPassthroughOptions = Pick<\n ApplicationOptions,\n | 'port'\n | 'apiPrefix'\n | 'defaultVersion'\n | 'middleware'\n | 'onError'\n | 'onNotFound'\n | 'plugins'\n | 'trustProxy'\n | 'jsonLimit'\n | 'security'\n | 'contributors'\n | 'contextStore'\n>\n\n/**\n * Options for creating a test application.\n * Disables helmet, cors, compression, and morgan by default.\n */\nexport interface CreateTestAppOptions extends BootstrapPassthroughOptions {\n modules: AppModuleClass[]\n /** Adapters to attach (auth, queue, devtools, etc.) */\n adapters?: AppAdapter[]\n /** DI overrides applied after module registration. Supports both string and symbol keys. */\n overrides?: Record<symbol | string, any>\n /**\n * Use an isolated container instead of the global singleton.\n * Prevents concurrent tests from interfering with each other's DI state.\n * When true, Container.create() is used instead of Container.reset() + getInstance().\n */\n isolated?: boolean\n}\n\n/**\n * Create an Application instance configured for testing.\n * Resets the DI container, registers modules, applies overrides,\n * and returns both the Application and its Express app.\n *\n * @example\n * ```ts\n * const { expressApp, container } = await createTestApp({\n * modules: [UserModule],\n * overrides: { [USER_REPO]: new InMemoryUserRepo() },\n * })\n * const res = await request(expressApp).get('/api/v1/users')\n * ```\n */\nexport async function createTestApp(options: CreateTestAppOptions): Promise<{\n app: Application\n expressApp: express.Express\n container: Container\n}> {\n let container: Container\n if (options.isolated) {\n // Isolated container — safe for concurrent tests\n container = Container.create()\n } else {\n // Global singleton — reset for serial test isolation (default)\n Container.reset()\n container = Container.getInstance()\n }\n\n const app = new Application({\n modules: options.modules,\n adapters: options.adapters,\n port: options.port,\n apiPrefix: options.apiPrefix,\n defaultVersion: options.defaultVersion,\n // Use provided middleware, or default to JSON body parsing only\n middleware: options.middleware ?? [express.json()],\n onError: options.onError,\n onNotFound: options.onNotFound,\n plugins: options.plugins,\n trustProxy: options.trustProxy,\n jsonLimit: options.jsonLimit,\n security: options.security,\n contributors: options.contributors,\n contextStore: options.contextStore,\n })\n\n // Run setup — mounts routes, registers modules, initializes adapters.\n // Awaited to support future async adapter hooks.\n await Promise.resolve(app.setup())\n\n // When using an isolated container, Application.setup() registers modules\n // on the global singleton (Container.getInstance()). Re-register them on\n // the isolated container so that bindings are available there too.\n if (options.isolated) {\n for (const ModuleClass of options.modules) {\n const mod = new ModuleClass()\n // register() is optional — see AppModule docs\n mod.register?.(container)\n }\n container.bootstrap()\n }\n\n // Apply DI overrides AFTER setup so they take precedence over\n // bindings registered by modules during register().\n if (options.overrides) {\n for (const token of Reflect.ownKeys(options.overrides)) {\n container.registerInstance(token, options.overrides[token as any])\n }\n }\n\n return {\n app,\n expressApp: app.getExpressApp(),\n container,\n }\n}\n\n/**\n * Build a quick TestModule that explicitly registers dependencies.\n * Useful for integration tests that need to control the DI graph.\n *\n * @example\n * ```ts\n * const TestModule = createTestModule({\n * register: (c) => {\n * c.registerFactory(USER_REPO, () => new InMemoryUserRepo())\n * c.register(UserController)\n * },\n * routes: () => buildRoutes(UserController, '/users'),\n * })\n * ```\n */\nexport function createTestModule(config: {\n register: (container: Container) => void\n routes: () => ModuleRoutes | ModuleRoutes[] | null\n}): AppModuleClass {\n class TestModule implements AppModule {\n register(container: Container) {\n config.register(container)\n }\n routes() {\n return config.routes()\n }\n }\n return TestModule\n}\n\n// ── Context Contributor unit-test helper (#107) ─────────────────────────\n\n/**\n * Options for {@link runContributor}.\n */\nexport interface RunContributorOptions {\n /**\n * Resolved deps passed to `resolve(ctx, deps)`. Skips the DI container\n * entirely — bypass for unit tests that want to assert pure resolve()\n * behaviour without standing up a container.\n *\n * Property names must match the spec's `deps` keys; values can be real\n * service instances, mocks, or test doubles.\n */\n deps?: Record<string, unknown>\n\n /**\n * Pre-populate the fake context's metadata Map. Useful for testing\n * contributors with `dependsOn` without running the full pipeline:\n * pre-populate the dependency keys, then assert that `resolve()` reads\n * them and produces the expected output.\n */\n initial?: Record<string, unknown>\n\n /** Override the fake context's `requestId` (default: `'test-req'`). */\n requestId?: string\n}\n\n/**\n * Result of {@link runContributor}.\n */\nexport interface RunContributorResult<K extends string> {\n /** Value returned by the contributor's `resolve()` call. */\n value: MetaValue<K>\n /** The fake `ExecutionContext` used during the run. */\n ctx: ExecutionContext\n /**\n * Final state of the fake context's metadata Map after `resolve()`.\n * Includes any `ctx.set(...)` calls the resolver made plus the final\n * resolved value under the contributor's own key.\n */\n meta: Map<string, unknown>\n}\n\n/**\n * Run a single context contributor in isolation against a fake\n * {@link ExecutionContext}. Skips the container, the topo-sort, and the\n * §20.9 error matrix — calls `decorator.registration.resolve(ctx, deps)`\n * directly so unit tests can assert pure resolve behaviour.\n *\n * Errors thrown by `resolve()` propagate so tests can `expect(...).rejects`\n * or `await expect(...).rejects.toThrow()` against them. To exercise the\n * full error matrix (optional skip, onError replacement, etc.), build a\n * one-element pipeline with `buildPipeline()` and use `runContributors()`\n * directly.\n *\n * @example\n * ```ts\n * const LoadProject = defineContextDecorator({\n * key: 'project',\n * dependsOn: ['tenant'],\n * deps: { repo: ProjectRepo },\n * resolve: (ctx, { repo }) => repo.findByTenant(ctx.get('tenant')!.id),\n * })\n *\n * const { value } = await runContributor(LoadProject, {\n * initial: { tenant: { id: 't-1' } },\n * deps: { repo: new InMemoryProjectRepo([{ id: 'p-1', tenantId: 't-1' }]) },\n * })\n * expect(value).toEqual({ id: 'p-1', tenantId: 't-1' })\n * ```\n */\nexport async function runContributor<\n K extends string,\n D extends Record<string, any> = Record<string, never>,\n>(\n decorator: ContextDecorator<K, D, ExecutionContext>,\n options: RunContributorOptions = {},\n): Promise<RunContributorResult<K>> {\n const meta = new Map<string, unknown>(Object.entries(options.initial ?? {}))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: options.requestId ?? 'test-req',\n }\n\n const value = await decorator.registration.resolve(ctx, (options.deps ?? {}) as never)\n meta.set(decorator.registration.key, value)\n\n return { value: value as MetaValue<K>, ctx, meta }\n}\n\n// ── Plugin unit-test harness (architecture.md §21.3.2) ──────────────────\n\n/**\n * Options for {@link createTestPlugin}.\n */\nexport interface CreateTestPluginOptions {\n /**\n * Use an isolated container (default: `true`). Isolated harnesses never\n * touch the global `Container.getInstance()` singleton, so concurrent\n * tests can run without stomping each other's DI state.\n */\n isolated?: boolean\n\n /**\n * Skip auto-invoking `plugin.register(container)` — useful when a test\n * wants to assert container state *before* the plugin touches it.\n * Defaults to `false` (register is called eagerly).\n */\n skipRegister?: boolean\n}\n\n/**\n * Result of {@link createTestPlugin}. Mirrors the spec sketch in\n * `architecture.md` §21.3.2 — `.container`, lifecycle invokers, and a\n * `runContributors()` helper that builds a one-plugin pipeline against a\n * fake `ExecutionContext`.\n */\nexport interface PluginTestHarness {\n /** The plugin under test — exposed for direct introspection. */\n readonly plugin: KickPlugin\n /** Isolated (or shared) DI container the plugin registered into. */\n readonly container: Container\n\n /**\n * Invoke `plugin.onReady(container)`. No-op if the plugin does not\n * define the hook.\n */\n callOnReady(): Promise<void>\n\n /**\n * Invoke `plugin.shutdown()`. No-op if the plugin does not define the\n * hook.\n */\n shutdown(): Promise<void>\n\n /**\n * Returns the module classes the plugin ships via `plugin.modules?()`.\n * The harness does **not** auto-instantiate them — use `createTestApp`\n * for that. Useful for assertions like \"the plugin exposes the module I\n * expect\".\n */\n modules(): AppModuleClass[]\n\n /**\n * Returns adapter instances the plugin ships via `plugin.adapters?()`.\n * Useful for testing the adapters alongside the plugin's DI bindings.\n */\n adapters(): AppAdapter[]\n\n /**\n * Returns middleware entries the plugin ships via `plugin.middleware?()`.\n */\n middleware(): any[]\n\n /**\n * Returns contributor registrations the plugin ships via\n * `plugin.contributors?()`.\n */\n contributors(): ContributorRegistration[]\n\n /**\n * Build a fake {@link ExecutionContext} pre-populated with the given\n * metadata. Symmetric with {@link runContributor}'s fake context.\n */\n makeContext(initial?: Record<string, unknown>): ExecutionContext\n\n /**\n * Run every contributor the plugin ships through a built pipeline\n * against the given context. Dependencies resolve through the harness's\n * container (same path production uses). Throws if the plugin's\n * contributors reference `dependsOn` keys no one in the plugin provides.\n */\n runContributors(ctx: ExecutionContext): Promise<void>\n}\n\n/**\n * Build an isolated test harness around a single {@link KickPlugin}.\n * Skips the full HTTP layer — symmetric with {@link runContributor} for\n * contributors and {@link createTestApp} for integration runs.\n *\n * @example\n * ```ts\n * const harness = await createTestPlugin(FlagsPlugin({ provider: scripted }))\n *\n * // The plugin's register() already ran — resolve any bindings.\n * const flags = harness.container.resolve(FLAGS_SERVICE)\n *\n * // Drive the post-bootstrap lifecycle.\n * await harness.callOnReady()\n *\n * // Exercise contributors shipped by the plugin.\n * const ctx = harness.makeContext({ requestId: 'req-1' })\n * await harness.runContributors(ctx)\n * expect(ctx.get('flags')).toEqual({ beta: true })\n *\n * await harness.shutdown()\n * ```\n */\nexport async function createTestPlugin(\n plugin: KickPlugin,\n options: CreateTestPluginOptions = {},\n): Promise<PluginTestHarness> {\n const isolated = options.isolated ?? true\n\n const container = isolated ? Container.create() : (Container.reset(), Container.getInstance())\n\n if (!options.skipRegister) plugin.register?.(container)\n\n return {\n plugin,\n container,\n\n async callOnReady() {\n await plugin.onReady?.(container)\n },\n\n async shutdown() {\n await plugin.shutdown?.()\n },\n\n modules() {\n return plugin.modules?.() ?? []\n },\n\n adapters() {\n return plugin.adapters?.() ?? []\n },\n\n middleware() {\n return plugin.middleware?.() ?? []\n },\n\n contributors() {\n return [...(plugin.contributors?.() ?? [])]\n },\n\n makeContext(initial: Record<string, unknown> = {}) {\n const meta = new Map<string, unknown>(Object.entries(initial))\n const ctx: ExecutionContext = {\n get(key) {\n return meta.get(key) as never\n },\n set(key, value) {\n meta.set(key, value)\n },\n requestId: 'test-req',\n }\n return ctx\n },\n\n async runContributors(ctx: ExecutionContext) {\n const regs = plugin.contributors?.() ?? []\n const sources = [...regs].map((registration) => ({\n registration,\n source: 'adapter' as const,\n label: plugin.name,\n }))\n const pipeline = buildPipeline(sources)\n await runContributors({ pipeline, ctx, container })\n },\n }\n}\n\n/** Alias for {@link createTestPlugin}, matching the `testPlugin` name used in the architecture spec. */\nexport const testPlugin = createTestPlugin\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,eAAsB,cAAc,SAIjC;CACD,IAAI;AACJ,KAAI,QAAQ,SAEV,aAAY,UAAU,QAAQ;MACzB;AAEL,YAAU,OAAO;AACjB,cAAY,UAAU,aAAa;;CAGrC,MAAM,MAAM,IAAI,YAAY;EAC1B,SAAS,QAAQ;EACjB,UAAU,QAAQ;EAClB,MAAM,QAAQ;EACd,WAAW,QAAQ;EACnB,gBAAgB,QAAQ;EAExB,YAAY,QAAQ,cAAc,CAAC,QAAQ,MAAM,CAAC;EAClD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OAER,UAAU,QAAQ,IAAI,UAAU,OAAO,EAAE,UAAU,aAAa;AAE7F,KAAI,CAAC,QAAQ,aAAc,QAAO,WAAW,UAAU;AAEvD,QAAO;EACL;EACA;EAEA,MAAM,cAAc;AAClB,SAAM,OAAO,UAAU,UAAU;;EAGnC,MAAM,WAAW;AACf,SAAM,OAAO,YAAY;;EAG3B,UAAU;AACR,UAAO,OAAO,WAAW,IAAI,EAAE;;EAGjC,WAAW;AACT,UAAO,OAAO,YAAY,IAAI,EAAE;;EAGlC,aAAa;AACX,UAAO,OAAO,cAAc,IAAI,EAAE;;EAGpC,eAAe;AACb,UAAO,CAAC,GAAI,OAAO,gBAAgB,IAAI,EAAE,CAAE;;EAG7C,YAAY,UAAmC,EAAE,EAAE;GACjD,MAAM,OAAO,IAAI,IAAqB,OAAO,QAAQ,QAAQ,CAAC;AAU9D,UAT8B;IAC5B,IAAI,KAAK;AACP,YAAO,KAAK,IAAI,IAAI;;IAEtB,IAAI,KAAK,OAAO;AACd,UAAK,IAAI,KAAK,MAAM;;IAEtB,WAAW;IACZ;;EAIH,MAAM,gBAAgB,KAAuB;AAQ3C,SAAM,gBAAgB;IAAE,UADP,cALD,CAAC,GADJ,OAAO,gBAAgB,IAAI,EAAE,CACjB,CAAC,KAAK,kBAAkB;KAC/C;KACA,QAAQ;KACR,OAAO,OAAO;KACf,EAAE,CACoC;IACL;IAAK;IAAW,CAAC;;EAEtD;;;AAIH,MAAa,aAAa"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forinda/kickjs-testing",
3
- "version": "3.2.0",
3
+ "version": "4.1.0",
4
4
  "description": "Test utilities, TestModule builder, and helpers for KickJS applications",
5
5
  "keywords": [
6
6
  "kickjs",
@@ -21,13 +21,10 @@
21
21
  "@forinda/kickjs",
22
22
  "@forinda/kickjs-auth",
23
23
  "@forinda/kickjs-cli",
24
- "@forinda/kickjs-config",
25
- "@forinda/kickjs-core",
26
24
  "@forinda/kickjs-cron",
27
25
  "@forinda/kickjs-devtools",
28
26
  "@forinda/kickjs-drizzle",
29
27
  "@forinda/kickjs-graphql",
30
- "@forinda/kickjs-http",
31
28
  "@forinda/kickjs-mailer",
32
29
  "@forinda/kickjs-multi-tenant",
33
30
  "@forinda/kickjs-notifications",
@@ -63,10 +60,7 @@
63
60
  "output": [
64
61
  "dist/**"
65
62
  ],
66
- "dependencies": [
67
- "../core:build",
68
- "../http:build"
69
- ]
63
+ "dependencies": []
70
64
  }
71
65
  },
72
66
  "dependencies": {},
@@ -75,16 +69,16 @@
75
69
  "@forinda/kickjs": ">=2.3.0"
76
70
  },
77
71
  "devDependencies": {
78
- "@swc/core": "^1.15.21",
72
+ "@swc/core": "^1.15.30",
79
73
  "@types/express": "^5.0.6",
80
- "@types/node": "^25.0.0",
81
- "@types/supertest": "^6.0.3",
74
+ "@types/node": "^25.6.0",
75
+ "@types/supertest": "^7.2.0",
82
76
  "express": "^5.1.0",
83
77
  "reflect-metadata": "^0.2.2",
84
78
  "supertest": "^7.2.2",
85
- "typescript": "^5.9.2",
86
- "vitest": "^4.1.2",
87
- "@forinda/kickjs": "3.2.0"
79
+ "typescript": "^6.0.3",
80
+ "vitest": "^4.1.5",
81
+ "@forinda/kickjs": "4.1.0"
88
82
  },
89
83
  "publishConfig": {
90
84
  "access": "public"