|
| 1 | +import { Transaction as KyselyTransaction } from "../../deps.ts"; |
| 2 | +import { _internals, Callback, closeDB, getDB } from "../utils.ts"; |
| 3 | +import begin from "./begin.ts"; |
| 4 | + |
| 5 | +type Maybe<T> = T | undefined; |
| 6 | + |
| 7 | +// deno-lint-ignore no-explicit-any |
| 8 | +type Transaction = KyselyTransaction<any>; |
| 9 | +let transaction: Maybe<Transaction>; |
| 10 | + |
| 11 | +let rollbackFn: Maybe<() => Promise<void>>; |
| 12 | + |
| 13 | +async function doWrapTransactionStub<T, U>( |
| 14 | + callback: Callback<T, U>, |
| 15 | +): Promise<U> { |
| 16 | + if (!transaction) { |
| 17 | + throw new Error("Transaction not initialized"); |
| 18 | + } |
| 19 | + |
| 20 | + try { |
| 21 | + const result = await callback(transaction); |
| 22 | + return result; |
| 23 | + } catch (error) { |
| 24 | + console.error("Transaction failed: ", error); |
| 25 | + |
| 26 | + throw error; |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +type Stub = { restore: () => unknown }; |
| 31 | + |
| 32 | +/** |
| 33 | + * Setup a database for testing. |
| 34 | + * |
| 35 | + * @param stub - The stub to use for wrapping the transaction. |
| 36 | + * @returns The `beforeAllFn`, `beforeEachFn`, `afterEachFn` and `afterAllFn` functions to use in your test suite. |
| 37 | + * @example |
| 38 | + * ```ts |
| 39 | + * import { stub } from "https://deno.land/std@0.210.0/testing/mock.ts"; |
| 40 | + * const { beforeEachFn, afterEachFn } = setupTesting(stub) |
| 41 | + * ``` |
| 42 | + */ |
| 43 | +export function setupTesting<T>( |
| 44 | + stub: (...args: unknown[]) => Stub, |
| 45 | +) { |
| 46 | + let transactionStub: Maybe<Stub>; |
| 47 | + |
| 48 | + // deno-lint-ignore require-await |
| 49 | + const beforeAllFn = async () => { |
| 50 | + getDB<T>(); |
| 51 | + }; |
| 52 | + |
| 53 | + const beforeEachFn = async () => { |
| 54 | + const db = getDB<T>(); |
| 55 | + |
| 56 | + const { trx, rollback } = await begin(db); |
| 57 | + transaction = trx; |
| 58 | + rollbackFn = rollback; |
| 59 | + |
| 60 | + transactionStub = stub( |
| 61 | + _internals, |
| 62 | + "doWrapTransaction", |
| 63 | + doWrapTransactionStub, |
| 64 | + ); |
| 65 | + }; |
| 66 | + |
| 67 | + const afterEachFn = async () => { |
| 68 | + if (transaction) { |
| 69 | + await rollbackFn?.(); |
| 70 | + transaction = undefined; |
| 71 | + } |
| 72 | + |
| 73 | + transactionStub?.restore(); |
| 74 | + }; |
| 75 | + |
| 76 | + const afterAllFn = async () => { |
| 77 | + await closeDB(); |
| 78 | + }; |
| 79 | + |
| 80 | + return { beforeAllFn, beforeEachFn, afterEachFn, afterAllFn }; |
| 81 | +} |
0 commit comments