Skip to content

Commit

Permalink
perf: fix mongoose setupFile performance issue
Browse files Browse the repository at this point in the history
  • Loading branch information
danielpza committed Sep 9, 2024
1 parent 29d137b commit b6ac0d6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/mongoose/setupFile.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import mongoose, { type Mongoose } from "mongoose";
import { afterEach, beforeEach, inject } from "vitest";
import { afterAll, afterEach, beforeAll, beforeEach, inject } from "vitest";
// hack to keep imported vitest types
export type { TestContext } from "vitest";
// hack to fix pnpm build issue
Expand All @@ -13,14 +13,23 @@ declare module "vitest" {
}
}

beforeEach(async (context) => {
let mongooseClient: Mongoose;

beforeAll(async () => {
const uri = inject("MONGO_URI");
mongooseClient = await mongoose.connect(uri);
});

const mongooseClient = await mongoose.connect(uri, { dbName: randomUUID() });
Object.assign(context, { mongoose: mongooseClient });
afterAll(async () => {
await mongooseClient.disconnect();
});

beforeEach(async (context) => {
const dbName = randomUUID();
mongooseClient.connection.useDb(dbName);
context.mongoose = mongooseClient;
});

afterEach(async (context) => {
await context.mongoose.connection.db?.dropDatabase();
await context.mongoose.disconnect();
});
6 changes: 6 additions & 0 deletions tests/mongoose-setup-file/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,9 @@ test("using mongoose schema", async ({ mongoose }) => {
await Users.create({ name: "John" });
expect(await Users.countDocuments()).toBe(1);
});

describe("performance", () => {
test.each(Array.from({ length: 1000 }, (_, i) => i))("test %i", async () => {
expect(true).toBe(true);
});
});

0 comments on commit b6ac0d6

Please # to comment.