Skip to content

Commit

Permalink
feat(testcontainers-mongo): use mongodb to clean collection instead o…
Browse files Browse the repository at this point in the history
…f @tsed/mongoose

The module can be used with mongoose or mikro-orm.
  • Loading branch information
Romakita committed Sep 8, 2024
1 parent f7e9953 commit d57e6cb
Show file tree
Hide file tree
Showing 13 changed files with 410 additions and 57 deletions.
1 change: 1 addition & 0 deletions packages/orm/mikro-orm/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"@tsed/json-mapper": "workspace:*",
"@tsed/logger": ">=6.7.5",
"@tsed/schema": "workspace:*",
"@tsed/testcontainers-mongo": "workspace:*",
"@tsed/typescript": "workspace:*",
"cross-env": "7.0.3",
"eslint": "^8.57.0",
Expand Down
23 changes: 13 additions & 10 deletions packages/orm/mikro-orm/test/integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,36 @@ import {Hooks} from "./helpers/services/Hooks.js";
import {UnmanagedEventSubscriber1} from "./helpers/services/UnmanagedEventSubscriber1.js";
import {UnmanagedEventSubscriber2} from "./helpers/services/UnmanagedEventSubscriber2.js";
import {UserService} from "./helpers/services/UserService.js";
import {TestContainersMongo} from "@tsed/testcontainers-mongo";

describe.skip("MikroOrm integration", () => {
describe("MikroOrm integration", () => {
let spiedLogger!: Logger;
let spiedTransactionalInterceptor!: TransactionalInterceptor;
let spiedHooks!: Hooks;

beforeEach(async () => {
// await TestMongooseContext.install({replicaSet: true});
// const {url: clientUrl} = await TestMongooseContext.getMongooseOptions();
const mongoSettings = TestContainersMongo.getMongoConnectionOptions();
const bstrp = PlatformTest.bootstrap(Server, {
disableComponentScan: true,
imports: [MikroOrmModule],
mikroOrm: [
defineConfig({
clientUrl,
clientUrl: mongoSettings.url,
entities: [User],
subscribers: [UnmanagedEventSubscriber1, new UnmanagedEventSubscriber2()]
subscribers: [UnmanagedEventSubscriber1, new UnmanagedEventSubscriber2()],
driverOptions: mongoSettings.connectionOptions
}),
defineConfig({
clientUrl,
clientUrl: mongoSettings.url,
contextName: "db1",
entities: [User]
entities: [User],
driverOptions: mongoSettings.connectionOptions
}),
defineConfig({
clientUrl,
clientUrl: mongoSettings.url,
contextName: "db2",
entities: [User]
entities: [User],
driverOptions: mongoSettings.connectionOptions
})
]
});
Expand All @@ -51,7 +54,7 @@ describe.skip("MikroOrm integration", () => {
afterEach(async () => {
reset<Hooks | TransactionalInterceptor | Logger>(spiedLogger, spiedTransactionalInterceptor, spiedHooks);

// await TestMongooseContext.reset();
await TestContainersMongo.reset();
});

it("should return repository", () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/orm/mikro-orm/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"path": "../../specs/schema/tsconfig.json"
},
{
"path": "../testing-mongoose/tsconfig.json"
"path": "../testcontainers-mongo/tsconfig.json"
},
{
"path": "./tsconfig.cjs.json"
Expand Down
4 changes: 3 additions & 1 deletion packages/orm/mikro-orm/vitest.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export default defineConfig(
...presets,
test: {
...presets.test,
// @ts-ignore
globalSetup: [import.meta.resolve("@tsed/testcontainers-mongo/vitest/setup")],
coverage: {
...presets.test.coverage,
thresholds: {
Expand All @@ -18,4 +20,4 @@ export default defineConfig(
}
}
}
);
);
1 change: 1 addition & 0 deletions packages/orm/mongoose/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"@tsed/json-mapper": "workspace:*",
"@tsed/logger": ">=6.7.5",
"@tsed/schema": "workspace:*",
"@tsed/testcontainers-mongo": "workspace:*",
"@tsed/typescript": "workspace:*",
"eslint": "^8.57.0",
"mongoose": "6.12.7",
Expand Down
5 changes: 3 additions & 2 deletions packages/orm/mongoose/test/array.integration.spec.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import {serialize} from "@tsed/json-mapper";
import {MyWorkspace, UserModel, UserWorkspace, Workspace, WorkspaceModel} from "./helpers/models/UserWorkspace.js";
import {TestContainersMongo} from "@tsed/testcontainers-mongo";
import {DITest} from "@tsed/di";

describe("Mongoose", () => {
describe("Array models", () => {
beforeEach(() => TestContainersMongo.create());
afterEach(() => TestContainersMongo.reset());

it("should run pre and post hook", async () => {
const userModel = PlatformTest.get<UserModel>(UserWorkspace);
const workspaceModel = PlatformTest.get<WorkspaceModel>(Workspace);
const userModel = DITest.get<UserModel>(UserWorkspace);
const workspaceModel = DITest.get<WorkspaceModel>(Workspace);

// GIVEN
const user = new userModel();
Expand Down
3 changes: 3 additions & 0 deletions packages/orm/mongoose/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
{
"path": "../../specs/schema/tsconfig.json"
},
{
"path": "../testcontainers-mongo/tsconfig.json"
},
{
"path": "./tsconfig.cjs.json"
},
Expand Down
10 changes: 0 additions & 10 deletions packages/orm/mongoose/vitest.setup.mts

This file was deleted.

4 changes: 2 additions & 2 deletions packages/orm/testcontainers-mongo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@
"@tsed/common": "workspace:*",
"@tsed/core": "workspace:*",
"@tsed/di": "workspace:*",
"@tsed/mongoose": "workspace:*",
"@tsed/typescript": "workspace:*",
"eslint": "^8.57.0",
"mongodb": "6.8.0",
"testcontainers": ">=10.11.0",
"typescript": "4.9.5"
},
Expand All @@ -45,7 +45,7 @@
"@tsed/common": "7.82.3",
"@tsed/core": "7.82.3",
"@tsed/di": "7.82.3",
"@tsed/mongoose": "7.82.3",
"mongodb": ">=6",
"testcontainers": ">=10.11.0"
}
}
43 changes: 42 additions & 1 deletion packages/orm/testcontainers-mongo/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,13 @@ export default defineConfig({

:::

### Usage
## Usage

### @tsed/mongoose

#### Unit test

Use the `TestContainersMongo.create` method to start the mongo server before your test:

```ts
import {PlatformTest} from "@tsed/common";
Expand Down Expand Up @@ -148,6 +154,41 @@ describe("UserModel", () => {
});
```

#### Integration test

Just use the `TestContainersMongo.bootstrap` method to start the mongo server before your test:

```ts
beforeEach(() => TestContainersMongo.bootstrap(Server, {}));
```

### Mikro ORM

TestContainersMongo provides a method to get the connection options for MikroORM:

```ts
import {EntityManager, MikroORM} from "@mikro-orm/core";
import {defineConfig} from "@mikro-orm/mongodb";
import {PlatformTest} from "@tsed/common";
import {TestContainersMongo} from "@tsed/testcontainers-mongo";

beforeEach(async () => {
const mongoSettings = TestContainersMongo.getMongoConnectionOptions();
const bstrp = PlatformTest.bootstrap(Server, {
disableComponentScan: true,
imports: [MikroOrmModule],
mikroOrm: [
defineConfig({
clientUrl: mongoSettings.url,
driverOptions: mongoSettings.connectionOptions,
entities: [User],
subscribers: [UnmanagedEventSubscriber1, new UnmanagedEventSubscriber2()]
})
]
});
});
```

## Contributors

Please read [contributing guidelines here](https://tsed.io/contributing.html)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {PlatformTest} from "@tsed/common";
import {MongooseService} from "@tsed/mongoose";
import {MongoClient} from "mongodb";
import {getMongoConnectionOptions, getMongoConnectionsOptions, startMongoServer, stopMongoServer} from "./ContainerUtils.js";

export class TestContainersMongo {
Expand All @@ -8,19 +8,25 @@ export class TestContainersMongo {
static getMongoConnectionsOptions = getMongoConnectionsOptions;
static getMongoConnectionOptions = getMongoConnectionOptions;

private static configuration: ReturnType<typeof getMongoConnectionsOptions>;

static create(options: Partial<TsED.Configuration> = {}) {
TestContainersMongo.configuration = getMongoConnectionsOptions();

return PlatformTest.create({
...options,
mongoose: getMongoConnectionsOptions()
mongoose: TestContainersMongo.configuration
});
}

static bootstrap(mod: unknown, opts: Partial<TsED.Configuration> = {}) {
return () =>
PlatformTest.bootstrap(mod, {
mongoose: getMongoConnectionsOptions(),
return () => {
TestContainersMongo.configuration = getMongoConnectionsOptions();
return PlatformTest.bootstrap(mod, {
mongoose: TestContainersMongo.configuration,
...opts
})();
};
}

static async reset(collectionName?: string) {
Expand All @@ -31,16 +37,18 @@ export class TestContainersMongo {
return PlatformTest.reset();
}

static async cleanCollection(collectionName: string) {
const service = PlatformTest.injector.get<MongooseService>(MongooseService)!;

const {collections} = service.get("default")!;

if (!collections[collectionName]) {
console.error(`Collection ${collectionName} not found. Here available collection names: ${Object.keys(collections)}`);
return;
static async cleanCollection(collectionName: string, mongoSettings = TestContainersMongo.configuration) {
try {
const client = new MongoClient(mongoSettings[0].url, {
directConnection: true
});

await client.connect();
const db = client.db();
await db.collection(collectionName).deleteMany({});
await client.close();
} catch (er) {
console.error(`Collection ${collectionName} not found. ${er.message} ${er.stack}`);
}

await collections[collectionName].deleteMany({});
}
}
3 changes: 0 additions & 3 deletions packages/orm/testcontainers-mongo/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@
{
"path": "../../di/tsconfig.json"
},
{
"path": "../mongoose/tsconfig.json"
},
{
"path": "./tsconfig.cjs.json"
},
Expand Down
Loading

0 comments on commit d57e6cb

Please sign in to comment.