@application-kit/testing 0.0.0-stage → 0.0.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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -2
  3. package/dist/cjs/build-web-application.d.ts +10 -0
  4. package/dist/cjs/build-web-application.js +23 -0
  5. package/dist/cjs/fake-microservice/fake-microservice-strategy.d.ts +12 -0
  6. package/dist/cjs/fake-microservice/fake-microservice-strategy.js +45 -0
  7. package/dist/cjs/fake-microservice/index.d.ts +1 -0
  8. package/dist/cjs/fake-microservice/index.js +17 -0
  9. package/dist/cjs/index.d.ts +8 -0
  10. package/dist/cjs/index.js +24 -0
  11. package/dist/cjs/package.json +3 -0
  12. package/dist/cjs/postgres/index.d.ts +1 -0
  13. package/dist/cjs/postgres/index.js +17 -0
  14. package/dist/cjs/postgres/test-data-source.d.ts +20 -0
  15. package/dist/cjs/postgres/test-data-source.js +46 -0
  16. package/dist/cjs/test-command-bus.d.ts +10 -0
  17. package/dist/cjs/test-command-bus.js +24 -0
  18. package/dist/cjs/test-event-bus.d.ts +6 -0
  19. package/dist/cjs/test-event-bus.js +22 -0
  20. package/dist/cjs/test-logger.d.ts +15 -0
  21. package/dist/cjs/test-logger.js +26 -0
  22. package/dist/cjs/test-query-bus.d.ts +12 -0
  23. package/dist/cjs/test-query-bus.js +26 -0
  24. package/dist/cjs/test-query-runner.d.ts +8 -0
  25. package/dist/cjs/test-query-runner.js +14 -0
  26. package/dist/esm/build-web-application.d.ts +10 -0
  27. package/dist/esm/build-web-application.js +19 -0
  28. package/dist/esm/fake-microservice/fake-microservice-strategy.d.ts +12 -0
  29. package/dist/esm/fake-microservice/fake-microservice-strategy.js +41 -0
  30. package/dist/esm/fake-microservice/index.d.ts +1 -0
  31. package/dist/esm/fake-microservice/index.js +1 -0
  32. package/dist/esm/index.d.ts +8 -0
  33. package/dist/esm/index.js +8 -0
  34. package/dist/esm/postgres/index.d.ts +1 -0
  35. package/dist/esm/postgres/index.js +1 -0
  36. package/dist/esm/postgres/test-data-source.d.ts +20 -0
  37. package/dist/esm/postgres/test-data-source.js +41 -0
  38. package/dist/esm/test-command-bus.d.ts +10 -0
  39. package/dist/esm/test-command-bus.js +19 -0
  40. package/dist/esm/test-event-bus.d.ts +6 -0
  41. package/dist/esm/test-event-bus.js +18 -0
  42. package/dist/esm/test-logger.d.ts +15 -0
  43. package/dist/esm/test-logger.js +22 -0
  44. package/dist/esm/test-query-bus.d.ts +12 -0
  45. package/dist/esm/test-query-bus.js +21 -0
  46. package/dist/esm/test-query-runner.d.ts +8 -0
  47. package/dist/esm/test-query-runner.js +11 -0
  48. package/package.json +86 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 application-kit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @application-kit/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Тестовая инфраструктура NestJS-приложений: стабы шин CQRS, логгер-накопитель, фейковый microservice-транспорт,
4
+ сборка web-приложения для e2e и Postgres в testcontainers. Для `devDependencies` приложения, в прод не попадает.
5
+
6
+ ## Установка
7
+
8
+ ```sh
9
+ yarn add --dev @application-kit/testing
10
+ ```
11
+
12
+ Peer-зависимости: `@nestjs/common`, `@nestjs/core`, `@nestjs/cqrs`,
13
+ `@nestjs/microservices`, `@nestjs/platform-fastify`, `@nestjs/testing`, `nestjs-pino`, `oxide.ts`, `rxjs`,
14
+ `testcontainers`, `typeorm`. Все обязательные: подпутей и опциональных peers нет.
15
+
16
+ ## Состав
17
+
18
+ - `TestLogger` — наследует `PinoLogger`, складывает вызовы в `debugs` / `errors` / `infos` / `warns`.
19
+ - `TestCommandBus` / `asCommandBus`, `TestQueryBus` / `asQueryBus` — стабы шин: фиксируют `executed`, отдают заданный результат.
20
+ - `TestEventBus` — `EventBus`, который копит события в `events`.
21
+ - `FakeMicroserviceStrategy` — транспорт microservice без сети.
22
+ - `buildWebApplication(imports, overrides, options)` — Fastify-приложение из реальных модулей с подменой провайдеров;
23
+ `testQueryRunner` закрепляет `QueryRunner` (отключается `pinQueryRunner: false`).
24
+ - `startPostgresContainer(image)`, `testDataSource({ image, migrations, entities, … })` — Postgres в контейнере и
25
+ инициализированный `DataSource`. Образ и стратегию имён передаёт приложение: версия БД и именование — его решение, у пакета их нет.
26
+
27
+ ```ts
28
+ const { dataSource } = await testDataSource({
29
+ entities: [UserOrmEntity],
30
+ image: 'postgres:18.3-alpine3.23',
31
+ migrations: [UserMigration],
32
+ namingStrategy: new TypeormPluralNamingStrategy(),
33
+ })
34
+ ```
@@ -0,0 +1,10 @@
1
+ import type { InjectionToken, ModuleMetadata } from '@nestjs/common';
2
+ import type { NestFastifyApplication } from '@nestjs/platform-fastify';
3
+ export interface BuildWebApplicationOptionsInterface {
4
+ pinQueryRunner?: boolean;
5
+ }
6
+ export interface ProviderOverrideInterface {
7
+ provide: InjectionToken;
8
+ useValue: unknown;
9
+ }
10
+ export declare const buildWebApplication: (importModules: NonNullable<ModuleMetadata["imports"]>, overrides?: ProviderOverrideInterface[], options?: BuildWebApplicationOptionsInterface) => Promise<NestFastifyApplication>;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildWebApplication = void 0;
4
+ const platform_fastify_1 = require("@nestjs/platform-fastify");
5
+ const testing_1 = require("@nestjs/testing");
6
+ const nestjs_pino_1 = require("nestjs-pino");
7
+ const test_query_runner_js_1 = require("./test-query-runner.js");
8
+ const queryRunnerProviders = (options) => (options.pinQueryRunner === false ? [] : [test_query_runner_js_1.testQueryRunner]);
9
+ const buildWebApplication = async (importModules, overrides = [], options = {}) => {
10
+ const builder = testing_1.Test.createTestingModule({
11
+ imports: importModules,
12
+ providers: queryRunnerProviders(options),
13
+ });
14
+ for (const override of overrides) {
15
+ builder.overrideProvider(override.provide).useValue(override.useValue);
16
+ }
17
+ const moduleFixture = await builder.compile();
18
+ const app = moduleFixture.createNestApplication(new platform_fastify_1.FastifyAdapter());
19
+ app.useLogger(app.get(nestjs_pino_1.Logger));
20
+ await app.init();
21
+ return app;
22
+ };
23
+ exports.buildWebApplication = buildWebApplication;
@@ -0,0 +1,12 @@
1
+ import type { CustomTransportStrategy, ReadPacket, WritePacket } from '@nestjs/microservices';
2
+ import { Server } from '@nestjs/microservices';
3
+ import { Subject } from 'rxjs';
4
+ export declare class FakeMicroserviceStrategy extends Server implements CustomTransportStrategy {
5
+ private readonly client;
6
+ private readonly server;
7
+ close(): void;
8
+ handleMessage(packet: ReadPacket): Promise<void>;
9
+ listen(listenCallback: () => void): void;
10
+ on(): void;
11
+ unwrap(): Subject<WritePacket<string>>;
12
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FakeMicroserviceStrategy = void 0;
4
+ const microservices_1 = require("@nestjs/microservices");
5
+ const rxjs_1 = require("rxjs");
6
+ class FakeMicroserviceStrategy extends microservices_1.Server {
7
+ client = new rxjs_1.Subject();
8
+ server = new rxjs_1.Subject();
9
+ close() {
10
+ }
11
+ async handleMessage(packet) {
12
+ const pattern = typeof packet.pattern === 'string' ? packet.pattern : '';
13
+ if (pattern === '') {
14
+ return;
15
+ }
16
+ const handler = this.getHandlerByPattern(pattern);
17
+ if (handler === null) {
18
+ return;
19
+ }
20
+ const context = new microservices_1.BaseRpcContext([packet.pattern]);
21
+ const response = this.transformToObservable(await handler(packet.data, context));
22
+ this.send(response, (data) => {
23
+ if (data.err === undefined) {
24
+ this.server.next(data);
25
+ }
26
+ else {
27
+ this.server.error(data.err);
28
+ }
29
+ });
30
+ }
31
+ listen(listenCallback) {
32
+ this.client.subscribe({
33
+ next: (packet) => {
34
+ void this.handleMessage(packet);
35
+ },
36
+ });
37
+ listenCallback();
38
+ }
39
+ on() {
40
+ }
41
+ unwrap() {
42
+ return this.server;
43
+ }
44
+ }
45
+ exports.FakeMicroserviceStrategy = FakeMicroserviceStrategy;
@@ -0,0 +1 @@
1
+ export * from './fake-microservice-strategy.js';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./fake-microservice-strategy.js"), exports);
@@ -0,0 +1,8 @@
1
+ export * from './fake-microservice/index.js';
2
+ export * from './postgres/index.js';
3
+ export * from './build-web-application.js';
4
+ export * from './test-command-bus.js';
5
+ export * from './test-event-bus.js';
6
+ export * from './test-logger.js';
7
+ export * from './test-query-bus.js';
8
+ export * from './test-query-runner.js';
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./fake-microservice/index.js"), exports);
18
+ __exportStar(require("./postgres/index.js"), exports);
19
+ __exportStar(require("./build-web-application.js"), exports);
20
+ __exportStar(require("./test-command-bus.js"), exports);
21
+ __exportStar(require("./test-event-bus.js"), exports);
22
+ __exportStar(require("./test-logger.js"), exports);
23
+ __exportStar(require("./test-query-bus.js"), exports);
24
+ __exportStar(require("./test-query-runner.js"), exports);
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1 @@
1
+ export * from './test-data-source.js';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./test-data-source.js"), exports);
@@ -0,0 +1,20 @@
1
+ import type { StartedTestContainer } from 'testcontainers';
2
+ import type { EntitySchema, MixedList, NamingStrategyInterface, QueryRunner } from 'typeorm';
3
+ import { DataSource } from 'typeorm';
4
+ export declare const TEST_DATABASE_NAME = "db";
5
+ export declare const TEST_DATABASE_PORT = 5432;
6
+ export declare const startPostgresContainer: (image: string) => Promise<StartedTestContainer>;
7
+ export interface TestDataSourceOptionsInterface {
8
+ entities: MixedList<EntitySchema | Function | string>;
9
+ image: string;
10
+ isLogging?: boolean;
11
+ migrations: MixedList<Function | string>;
12
+ namingStrategy: NamingStrategyInterface;
13
+ shouldSynchronize?: boolean;
14
+ }
15
+ export interface TestDataSourceResultInterface {
16
+ container: StartedTestContainer;
17
+ dataSource: DataSource;
18
+ queryRunner: QueryRunner;
19
+ }
20
+ export declare const testDataSource: ({ entities, image, isLogging, migrations, namingStrategy, shouldSynchronize, }: TestDataSourceOptionsInterface) => Promise<TestDataSourceResultInterface>;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.testDataSource = exports.startPostgresContainer = exports.TEST_DATABASE_PORT = exports.TEST_DATABASE_NAME = void 0;
4
+ const testcontainers_1 = require("testcontainers");
5
+ const typeorm_1 = require("typeorm");
6
+ exports.TEST_DATABASE_NAME = 'db';
7
+ exports.TEST_DATABASE_PORT = 5432;
8
+ const startPostgresContainer = async (image) => new testcontainers_1.GenericContainer(image)
9
+ .withStartupTimeout(120_000)
10
+ .withWaitStrategy(testcontainers_1.Wait.forLogMessage(/database system is ready to accept connections/u, 2))
11
+ .withEnvironment({
12
+ POSTGRES_DATABASE: exports.TEST_DATABASE_NAME,
13
+ POSTGRES_PASSWORD: exports.TEST_DATABASE_NAME,
14
+ POSTGRES_USER: exports.TEST_DATABASE_NAME,
15
+ })
16
+ .withExposedPorts(exports.TEST_DATABASE_PORT)
17
+ .start();
18
+ exports.startPostgresContainer = startPostgresContainer;
19
+ const testDataSource = async ({ entities, image, isLogging = false, migrations, namingStrategy, shouldSynchronize = false, }) => {
20
+ const databaseName = exports.TEST_DATABASE_NAME;
21
+ const databasePort = exports.TEST_DATABASE_PORT;
22
+ const container = await (0, exports.startPostgresContainer)(image);
23
+ const databaseConfig = {
24
+ database: databaseName,
25
+ entities,
26
+ host: container.getHost(),
27
+ logging: isLogging,
28
+ maxQueryExecutionTime: 1000,
29
+ migrations,
30
+ migrationsRun: !shouldSynchronize,
31
+ namingStrategy,
32
+ password: databaseName,
33
+ port: container.getMappedPort(databasePort),
34
+ ssl: false,
35
+ subscribers: [],
36
+ synchronize: shouldSynchronize,
37
+ type: 'postgres',
38
+ username: databaseName,
39
+ };
40
+ const dataSource = new typeorm_1.DataSource(databaseConfig);
41
+ await dataSource.initialize();
42
+ const queryRunner = dataSource.createQueryRunner();
43
+ Object.assign(dataSource.manager, { queryRunner });
44
+ return { container, dataSource, queryRunner };
45
+ };
46
+ exports.testDataSource = testDataSource;
@@ -0,0 +1,10 @@
1
+ import type { CommandBus, ICommand } from '@nestjs/cqrs';
2
+ export declare class TestCommandBus {
3
+ readonly executed: ICommand[];
4
+ private executeResult;
5
+ private readonly queuedResults;
6
+ execute<TResult = unknown>(command: ICommand): Promise<TResult>;
7
+ setExecuteResult(result: unknown): void;
8
+ setExecuteResults(results: unknown[]): void;
9
+ }
10
+ export declare const asCommandBus: (fake: TestCommandBus) => CommandBus;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.asCommandBus = exports.TestCommandBus = void 0;
4
+ const oxide_ts_1 = require("oxide.ts");
5
+ class TestCommandBus {
6
+ executed = [];
7
+ executeResult = (0, oxide_ts_1.Ok)('');
8
+ queuedResults = [];
9
+ async execute(command) {
10
+ await Promise.resolve();
11
+ this.executed.push(command);
12
+ const result = this.queuedResults.length > 0 ? this.queuedResults.shift() : this.executeResult;
13
+ return result;
14
+ }
15
+ setExecuteResult(result) {
16
+ this.executeResult = result;
17
+ }
18
+ setExecuteResults(results) {
19
+ this.queuedResults.splice(0, this.queuedResults.length, ...results);
20
+ }
21
+ }
22
+ exports.TestCommandBus = TestCommandBus;
23
+ const asCommandBus = (fake) => fake;
24
+ exports.asCommandBus = asCommandBus;
@@ -0,0 +1,6 @@
1
+ import { EventBus } from '@nestjs/cqrs';
2
+ export declare class TestEventBus extends EventBus {
3
+ readonly events: Set<unknown>;
4
+ constructor();
5
+ cleanEvents(): void;
6
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TestEventBus = void 0;
4
+ const cqrs_1 = require("@nestjs/cqrs");
5
+ class TestEventBus extends cqrs_1.EventBus {
6
+ events = new Set();
7
+ constructor() {
8
+ const moduleReference = {};
9
+ const commandBus = {};
10
+ const unhandledExceptionBus = {};
11
+ super(commandBus, moduleReference, unhandledExceptionBus);
12
+ this.publisher = {
13
+ publish: (event) => {
14
+ this.events.add(event);
15
+ },
16
+ };
17
+ }
18
+ cleanEvents() {
19
+ this.events.clear();
20
+ }
21
+ }
22
+ exports.TestEventBus = TestEventBus;
@@ -0,0 +1,15 @@
1
+ import { PinoLogger } from 'nestjs-pino';
2
+ export interface TestLogEntryInterface {
3
+ readonly args: readonly unknown[];
4
+ }
5
+ export declare class TestLogger extends PinoLogger {
6
+ readonly debugs: TestLogEntryInterface[];
7
+ readonly errors: TestLogEntryInterface[];
8
+ readonly infos: TestLogEntryInterface[];
9
+ readonly warns: TestLogEntryInterface[];
10
+ constructor();
11
+ debug(...arguments_: unknown[]): void;
12
+ error(...arguments_: unknown[]): void;
13
+ info(...arguments_: unknown[]): void;
14
+ warn(...arguments_: unknown[]): void;
15
+ }
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TestLogger = void 0;
4
+ const nestjs_pino_1 = require("nestjs-pino");
5
+ class TestLogger extends nestjs_pino_1.PinoLogger {
6
+ debugs = [];
7
+ errors = [];
8
+ infos = [];
9
+ warns = [];
10
+ constructor() {
11
+ super({});
12
+ }
13
+ debug(...arguments_) {
14
+ this.debugs.push({ args: arguments_ });
15
+ }
16
+ error(...arguments_) {
17
+ this.errors.push({ args: arguments_ });
18
+ }
19
+ info(...arguments_) {
20
+ this.infos.push({ args: arguments_ });
21
+ }
22
+ warn(...arguments_) {
23
+ this.warns.push({ args: arguments_ });
24
+ }
25
+ }
26
+ exports.TestLogger = TestLogger;
@@ -0,0 +1,12 @@
1
+ import type { IQuery, QueryBus } from '@nestjs/cqrs';
2
+ export declare class TestQueryBus {
3
+ readonly executed: IQuery[];
4
+ private executeResult;
5
+ private readonly executeResultsByQuery;
6
+ execute<TResult = unknown>(query: IQuery): Promise<TResult>;
7
+ setExecuteResult(result: unknown): void;
8
+ setExecuteResultFor(queryClass: {
9
+ name: string;
10
+ }, result: unknown): void;
11
+ }
12
+ export declare const asQueryBus: (fake: TestQueryBus) => QueryBus;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.asQueryBus = exports.TestQueryBus = void 0;
4
+ class TestQueryBus {
5
+ executed = [];
6
+ executeResult = null;
7
+ executeResultsByQuery = new Map();
8
+ async execute(query) {
9
+ await Promise.resolve();
10
+ this.executed.push(query);
11
+ const queryName = query.constructor.name;
12
+ const result = this.executeResultsByQuery.has(queryName)
13
+ ? this.executeResultsByQuery.get(queryName)
14
+ : this.executeResult;
15
+ return result;
16
+ }
17
+ setExecuteResult(result) {
18
+ this.executeResult = result;
19
+ }
20
+ setExecuteResultFor(queryClass, result) {
21
+ this.executeResultsByQuery.set(queryClass.name, result);
22
+ }
23
+ }
24
+ exports.TestQueryBus = TestQueryBus;
25
+ const asQueryBus = (fake) => fake;
26
+ exports.asQueryBus = asQueryBus;
@@ -0,0 +1,8 @@
1
+ import type { QueryRunner } from 'typeorm';
2
+ import { DataSource, EntityManager } from 'typeorm';
3
+ export declare const TEST_QUERY_RUNNER: unique symbol;
4
+ export declare const testQueryRunner: {
5
+ inject: (typeof DataSource | typeof EntityManager)[];
6
+ provide: symbol;
7
+ useFactory: (dataSource: DataSource, manager: EntityManager) => QueryRunner;
8
+ };
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.testQueryRunner = exports.TEST_QUERY_RUNNER = void 0;
4
+ const typeorm_1 = require("typeorm");
5
+ exports.TEST_QUERY_RUNNER = Symbol('TEST_QUERY_RUNNER');
6
+ exports.testQueryRunner = {
7
+ inject: [typeorm_1.DataSource, typeorm_1.EntityManager],
8
+ provide: exports.TEST_QUERY_RUNNER,
9
+ useFactory: (dataSource, manager) => {
10
+ const queryRunner = dataSource.createQueryRunner();
11
+ Object.assign(manager, { queryRunner });
12
+ return queryRunner;
13
+ },
14
+ };
@@ -0,0 +1,10 @@
1
+ import type { InjectionToken, ModuleMetadata } from '@nestjs/common';
2
+ import type { NestFastifyApplication } from '@nestjs/platform-fastify';
3
+ export interface BuildWebApplicationOptionsInterface {
4
+ pinQueryRunner?: boolean;
5
+ }
6
+ export interface ProviderOverrideInterface {
7
+ provide: InjectionToken;
8
+ useValue: unknown;
9
+ }
10
+ export declare const buildWebApplication: (importModules: NonNullable<ModuleMetadata["imports"]>, overrides?: ProviderOverrideInterface[], options?: BuildWebApplicationOptionsInterface) => Promise<NestFastifyApplication>;
@@ -0,0 +1,19 @@
1
+ import { FastifyAdapter } from '@nestjs/platform-fastify';
2
+ import { Test } from '@nestjs/testing';
3
+ import { Logger } from 'nestjs-pino';
4
+ import { testQueryRunner } from './test-query-runner.js';
5
+ const queryRunnerProviders = (options) => (options.pinQueryRunner === false ? [] : [testQueryRunner]);
6
+ export const buildWebApplication = async (importModules, overrides = [], options = {}) => {
7
+ const builder = Test.createTestingModule({
8
+ imports: importModules,
9
+ providers: queryRunnerProviders(options),
10
+ });
11
+ for (const override of overrides) {
12
+ builder.overrideProvider(override.provide).useValue(override.useValue);
13
+ }
14
+ const moduleFixture = await builder.compile();
15
+ const app = moduleFixture.createNestApplication(new FastifyAdapter());
16
+ app.useLogger(app.get(Logger));
17
+ await app.init();
18
+ return app;
19
+ };
@@ -0,0 +1,12 @@
1
+ import type { CustomTransportStrategy, ReadPacket, WritePacket } from '@nestjs/microservices';
2
+ import { Server } from '@nestjs/microservices';
3
+ import { Subject } from 'rxjs';
4
+ export declare class FakeMicroserviceStrategy extends Server implements CustomTransportStrategy {
5
+ private readonly client;
6
+ private readonly server;
7
+ close(): void;
8
+ handleMessage(packet: ReadPacket): Promise<void>;
9
+ listen(listenCallback: () => void): void;
10
+ on(): void;
11
+ unwrap(): Subject<WritePacket<string>>;
12
+ }
@@ -0,0 +1,41 @@
1
+ import { BaseRpcContext, Server, } from '@nestjs/microservices';
2
+ import { Subject } from 'rxjs';
3
+ export class FakeMicroserviceStrategy extends Server {
4
+ client = new Subject();
5
+ server = new Subject();
6
+ close() {
7
+ }
8
+ async handleMessage(packet) {
9
+ const pattern = typeof packet.pattern === 'string' ? packet.pattern : '';
10
+ if (pattern === '') {
11
+ return;
12
+ }
13
+ const handler = this.getHandlerByPattern(pattern);
14
+ if (handler === null) {
15
+ return;
16
+ }
17
+ const context = new BaseRpcContext([packet.pattern]);
18
+ const response = this.transformToObservable(await handler(packet.data, context));
19
+ this.send(response, (data) => {
20
+ if (data.err === undefined) {
21
+ this.server.next(data);
22
+ }
23
+ else {
24
+ this.server.error(data.err);
25
+ }
26
+ });
27
+ }
28
+ listen(listenCallback) {
29
+ this.client.subscribe({
30
+ next: (packet) => {
31
+ void this.handleMessage(packet);
32
+ },
33
+ });
34
+ listenCallback();
35
+ }
36
+ on() {
37
+ }
38
+ unwrap() {
39
+ return this.server;
40
+ }
41
+ }
@@ -0,0 +1 @@
1
+ export * from './fake-microservice-strategy.js';
@@ -0,0 +1 @@
1
+ export * from './fake-microservice-strategy.js';
@@ -0,0 +1,8 @@
1
+ export * from './fake-microservice/index.js';
2
+ export * from './postgres/index.js';
3
+ export * from './build-web-application.js';
4
+ export * from './test-command-bus.js';
5
+ export * from './test-event-bus.js';
6
+ export * from './test-logger.js';
7
+ export * from './test-query-bus.js';
8
+ export * from './test-query-runner.js';
@@ -0,0 +1,8 @@
1
+ export * from './fake-microservice/index.js';
2
+ export * from './postgres/index.js';
3
+ export * from './build-web-application.js';
4
+ export * from './test-command-bus.js';
5
+ export * from './test-event-bus.js';
6
+ export * from './test-logger.js';
7
+ export * from './test-query-bus.js';
8
+ export * from './test-query-runner.js';
@@ -0,0 +1 @@
1
+ export * from './test-data-source.js';
@@ -0,0 +1 @@
1
+ export * from './test-data-source.js';
@@ -0,0 +1,20 @@
1
+ import type { StartedTestContainer } from 'testcontainers';
2
+ import type { EntitySchema, MixedList, NamingStrategyInterface, QueryRunner } from 'typeorm';
3
+ import { DataSource } from 'typeorm';
4
+ export declare const TEST_DATABASE_NAME = "db";
5
+ export declare const TEST_DATABASE_PORT = 5432;
6
+ export declare const startPostgresContainer: (image: string) => Promise<StartedTestContainer>;
7
+ export interface TestDataSourceOptionsInterface {
8
+ entities: MixedList<EntitySchema | Function | string>;
9
+ image: string;
10
+ isLogging?: boolean;
11
+ migrations: MixedList<Function | string>;
12
+ namingStrategy: NamingStrategyInterface;
13
+ shouldSynchronize?: boolean;
14
+ }
15
+ export interface TestDataSourceResultInterface {
16
+ container: StartedTestContainer;
17
+ dataSource: DataSource;
18
+ queryRunner: QueryRunner;
19
+ }
20
+ export declare const testDataSource: ({ entities, image, isLogging, migrations, namingStrategy, shouldSynchronize, }: TestDataSourceOptionsInterface) => Promise<TestDataSourceResultInterface>;
@@ -0,0 +1,41 @@
1
+ import { GenericContainer, Wait } from 'testcontainers';
2
+ import { DataSource } from 'typeorm';
3
+ export const TEST_DATABASE_NAME = 'db';
4
+ export const TEST_DATABASE_PORT = 5432;
5
+ export const startPostgresContainer = async (image) => new GenericContainer(image)
6
+ .withStartupTimeout(120_000)
7
+ .withWaitStrategy(Wait.forLogMessage(/database system is ready to accept connections/u, 2))
8
+ .withEnvironment({
9
+ POSTGRES_DATABASE: TEST_DATABASE_NAME,
10
+ POSTGRES_PASSWORD: TEST_DATABASE_NAME,
11
+ POSTGRES_USER: TEST_DATABASE_NAME,
12
+ })
13
+ .withExposedPorts(TEST_DATABASE_PORT)
14
+ .start();
15
+ export const testDataSource = async ({ entities, image, isLogging = false, migrations, namingStrategy, shouldSynchronize = false, }) => {
16
+ const databaseName = TEST_DATABASE_NAME;
17
+ const databasePort = TEST_DATABASE_PORT;
18
+ const container = await startPostgresContainer(image);
19
+ const databaseConfig = {
20
+ database: databaseName,
21
+ entities,
22
+ host: container.getHost(),
23
+ logging: isLogging,
24
+ maxQueryExecutionTime: 1000,
25
+ migrations,
26
+ migrationsRun: !shouldSynchronize,
27
+ namingStrategy,
28
+ password: databaseName,
29
+ port: container.getMappedPort(databasePort),
30
+ ssl: false,
31
+ subscribers: [],
32
+ synchronize: shouldSynchronize,
33
+ type: 'postgres',
34
+ username: databaseName,
35
+ };
36
+ const dataSource = new DataSource(databaseConfig);
37
+ await dataSource.initialize();
38
+ const queryRunner = dataSource.createQueryRunner();
39
+ Object.assign(dataSource.manager, { queryRunner });
40
+ return { container, dataSource, queryRunner };
41
+ };
@@ -0,0 +1,10 @@
1
+ import type { CommandBus, ICommand } from '@nestjs/cqrs';
2
+ export declare class TestCommandBus {
3
+ readonly executed: ICommand[];
4
+ private executeResult;
5
+ private readonly queuedResults;
6
+ execute<TResult = unknown>(command: ICommand): Promise<TResult>;
7
+ setExecuteResult(result: unknown): void;
8
+ setExecuteResults(results: unknown[]): void;
9
+ }
10
+ export declare const asCommandBus: (fake: TestCommandBus) => CommandBus;
@@ -0,0 +1,19 @@
1
+ import { Ok } from 'oxide.ts';
2
+ export class TestCommandBus {
3
+ executed = [];
4
+ executeResult = Ok('');
5
+ queuedResults = [];
6
+ async execute(command) {
7
+ await Promise.resolve();
8
+ this.executed.push(command);
9
+ const result = this.queuedResults.length > 0 ? this.queuedResults.shift() : this.executeResult;
10
+ return result;
11
+ }
12
+ setExecuteResult(result) {
13
+ this.executeResult = result;
14
+ }
15
+ setExecuteResults(results) {
16
+ this.queuedResults.splice(0, this.queuedResults.length, ...results);
17
+ }
18
+ }
19
+ export const asCommandBus = (fake) => fake;
@@ -0,0 +1,6 @@
1
+ import { EventBus } from '@nestjs/cqrs';
2
+ export declare class TestEventBus extends EventBus {
3
+ readonly events: Set<unknown>;
4
+ constructor();
5
+ cleanEvents(): void;
6
+ }
@@ -0,0 +1,18 @@
1
+ import { EventBus } from '@nestjs/cqrs';
2
+ export class TestEventBus extends EventBus {
3
+ events = new Set();
4
+ constructor() {
5
+ const moduleReference = {};
6
+ const commandBus = {};
7
+ const unhandledExceptionBus = {};
8
+ super(commandBus, moduleReference, unhandledExceptionBus);
9
+ this.publisher = {
10
+ publish: (event) => {
11
+ this.events.add(event);
12
+ },
13
+ };
14
+ }
15
+ cleanEvents() {
16
+ this.events.clear();
17
+ }
18
+ }
@@ -0,0 +1,15 @@
1
+ import { PinoLogger } from 'nestjs-pino';
2
+ export interface TestLogEntryInterface {
3
+ readonly args: readonly unknown[];
4
+ }
5
+ export declare class TestLogger extends PinoLogger {
6
+ readonly debugs: TestLogEntryInterface[];
7
+ readonly errors: TestLogEntryInterface[];
8
+ readonly infos: TestLogEntryInterface[];
9
+ readonly warns: TestLogEntryInterface[];
10
+ constructor();
11
+ debug(...arguments_: unknown[]): void;
12
+ error(...arguments_: unknown[]): void;
13
+ info(...arguments_: unknown[]): void;
14
+ warn(...arguments_: unknown[]): void;
15
+ }
@@ -0,0 +1,22 @@
1
+ import { PinoLogger } from 'nestjs-pino';
2
+ export class TestLogger extends PinoLogger {
3
+ debugs = [];
4
+ errors = [];
5
+ infos = [];
6
+ warns = [];
7
+ constructor() {
8
+ super({});
9
+ }
10
+ debug(...arguments_) {
11
+ this.debugs.push({ args: arguments_ });
12
+ }
13
+ error(...arguments_) {
14
+ this.errors.push({ args: arguments_ });
15
+ }
16
+ info(...arguments_) {
17
+ this.infos.push({ args: arguments_ });
18
+ }
19
+ warn(...arguments_) {
20
+ this.warns.push({ args: arguments_ });
21
+ }
22
+ }
@@ -0,0 +1,12 @@
1
+ import type { IQuery, QueryBus } from '@nestjs/cqrs';
2
+ export declare class TestQueryBus {
3
+ readonly executed: IQuery[];
4
+ private executeResult;
5
+ private readonly executeResultsByQuery;
6
+ execute<TResult = unknown>(query: IQuery): Promise<TResult>;
7
+ setExecuteResult(result: unknown): void;
8
+ setExecuteResultFor(queryClass: {
9
+ name: string;
10
+ }, result: unknown): void;
11
+ }
12
+ export declare const asQueryBus: (fake: TestQueryBus) => QueryBus;
@@ -0,0 +1,21 @@
1
+ export class TestQueryBus {
2
+ executed = [];
3
+ executeResult = null;
4
+ executeResultsByQuery = new Map();
5
+ async execute(query) {
6
+ await Promise.resolve();
7
+ this.executed.push(query);
8
+ const queryName = query.constructor.name;
9
+ const result = this.executeResultsByQuery.has(queryName)
10
+ ? this.executeResultsByQuery.get(queryName)
11
+ : this.executeResult;
12
+ return result;
13
+ }
14
+ setExecuteResult(result) {
15
+ this.executeResult = result;
16
+ }
17
+ setExecuteResultFor(queryClass, result) {
18
+ this.executeResultsByQuery.set(queryClass.name, result);
19
+ }
20
+ }
21
+ export const asQueryBus = (fake) => fake;
@@ -0,0 +1,8 @@
1
+ import type { QueryRunner } from 'typeorm';
2
+ import { DataSource, EntityManager } from 'typeorm';
3
+ export declare const TEST_QUERY_RUNNER: unique symbol;
4
+ export declare const testQueryRunner: {
5
+ inject: (typeof DataSource | typeof EntityManager)[];
6
+ provide: symbol;
7
+ useFactory: (dataSource: DataSource, manager: EntityManager) => QueryRunner;
8
+ };
@@ -0,0 +1,11 @@
1
+ import { DataSource, EntityManager } from 'typeorm';
2
+ export const TEST_QUERY_RUNNER = Symbol('TEST_QUERY_RUNNER');
3
+ export const testQueryRunner = {
4
+ inject: [DataSource, EntityManager],
5
+ provide: TEST_QUERY_RUNNER,
6
+ useFactory: (dataSource, manager) => {
7
+ const queryRunner = dataSource.createQueryRunner();
8
+ Object.assign(manager, { queryRunner });
9
+ return queryRunner;
10
+ },
11
+ };
package/package.json CHANGED
@@ -1,6 +1,89 @@
1
1
  {
2
2
  "name": "@application-kit/testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.0",
4
+ "description": "Тестовая инфраструктура NestJS-приложений: шины CQRS, логгер, фейковый microservice, сборка web-приложения и Postgres в testcontainers",
5
+ "keywords": [
6
+ "cqrs",
7
+ "nestjs",
8
+ "testcontainers",
9
+ "testing"
10
+ ],
11
+ "homepage": "https://gitlab.com/application-kit/application-kit/-/tree/main/packages/testing",
12
+ "bugs": "https://gitlab.com/application-kit/application-kit/-/issues",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://gitlab.com/application-kit/application-kit.git",
16
+ "directory": "packages/testing"
17
+ },
18
+ "license": "MIT",
19
+ "author": {
20
+ "name": "application-kit"
21
+ },
22
+ "sideEffects": false,
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "import": {
27
+ "types": "./dist/esm/index.d.ts",
28
+ "default": "./dist/esm/index.js"
29
+ },
30
+ "require": {
31
+ "types": "./dist/cjs/index.d.ts",
32
+ "default": "./dist/cjs/index.js"
33
+ }
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "main": "./dist/cjs/index.js",
38
+ "module": "./dist/esm/index.js",
39
+ "types": "./dist/cjs/index.d.ts",
40
+ "files": [
41
+ "dist"
42
+ ],
43
+ "scripts": {
44
+ "build": "rm -rf ./dist && node ../../scripts/barrels.mjs create ./src && tsc --project tsconfig.build.json && tsc --project tsconfig.build.cjs.json && node ../../scripts/barrels.mjs clean ./src && node ../../scripts/mark-cjs.mjs ./dist/cjs",
45
+ "lint:tsc": "tsc --noEmit --pretty --project .",
46
+ "test:mutation": "stryker run",
47
+ "test:unit": "vitest run"
48
+ },
49
+ "devDependencies": {
50
+ "@nestjs/common": "^11.2.7",
51
+ "@nestjs/core": "^11.2.7",
52
+ "@nestjs/cqrs": "^11.0.3",
53
+ "@nestjs/microservices": "^11.2.7",
54
+ "@nestjs/platform-fastify": "^11.2.7",
55
+ "@nestjs/testing": "^11.2.7",
56
+ "@stryker-mutator/core": "^10.0.0",
57
+ "@stryker-mutator/vitest-runner": "^10.0.0",
58
+ "@types/node": "^26.2.0",
59
+ "nestjs-pino": "^4.6.1",
60
+ "oxide.ts": "^1.1.0",
61
+ "pino": "^10.3.1",
62
+ "pino-http": "^11.0.0",
63
+ "reflect-metadata": "^0.2.2",
64
+ "rxjs": "^7.8.2",
65
+ "testcontainers": "12.1.0",
66
+ "typeorm": "^1.1.0",
67
+ "typescript": "^6.0.3",
68
+ "vitest": "^4.1.11"
69
+ },
70
+ "peerDependencies": {
71
+ "@nestjs/common": "^11.0.0",
72
+ "@nestjs/core": "^11.0.0",
73
+ "@nestjs/cqrs": "^11.0.3",
74
+ "@nestjs/microservices": "^11.0.0",
75
+ "@nestjs/platform-fastify": "^11.0.0",
76
+ "@nestjs/testing": "^11.0.0",
77
+ "nestjs-pino": "^4.6.1",
78
+ "oxide.ts": "^1.1.0",
79
+ "rxjs": "^7.8.2",
80
+ "testcontainers": "^12.1.0",
81
+ "typeorm": "^1.0.0"
82
+ },
83
+ "engines": {
84
+ "node": ">=24"
85
+ },
86
+ "publishConfig": {
87
+ "access": "public"
88
+ }
6
89
  }