How to wrap each test within a function? #3232
Unanswered
Eldemarkki
asked this question in
Q&A
Replies: 1 comment
-
|
Given the number of reactions, I thought would be nice to provide an alternative approach on how to achieve this. I am using kylsey but you can apply the same idea with very few changes using Prisma or any another database access library. import { describe, test } from "vitest";
import type { Kysely, Transaction } from "kysely";
export { describe, beforeAll, afterAll } from "vitest";
// This is our custom test context. Read more about test context here in official docs: https://vitest.dev/guide/test-context
interface DatabaseFixture {
trx: Transaction<Database>;
}
const withDatabaseTransaction = test.extend<DatabaseFixture>({
// eslint-disable-next-line no-empty-pattern
trx: async ({}, use) => {
const database: Kysely<Database> = await getDatabase();
try {
await database.transaction().execute(async (trx: Transaction<Database>) => {
await use(trx);
// there is no way to rollback in kysely, so we throw an error to simulate a rollback
throw new KyseleyRollbackError();
});
} catch (err) {
const isRollbackError = err instanceof KyseleyRollbackError;
if (!isRollbackError) {
throw err;
}
}
}
});
describe("Test 1", () => {
withDatabaseTransaction("run in transaction", async ({ trx }) => {
// use trx here
});
});
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface Database {} // Kyseley database interface
function getDatabase(): Promise<Kysely<Database>> {
// create a singleton Kyseley instance and return it
throw new Error("Function not implemented");
}
class KyseleyRollbackError extends Error {} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm making integration tests that depend on the database. I'd like each test to be run inside a database transaction, so that I can cancel the changes after running the tests. That would require wrapping each test inside a transaction, like in the following code:
That would be identical to the following code:
Obviously that doesn't work since the
wrapEachfunction doesn't exist, but is there anything already existing that I could use to replicate that behaviour?Beta Was this translation helpful? Give feedback.
All reactions