I'm trying to run tests in parallel using slonik. Each jest worker creates his own pool. All SQL queries in one test case must be executed inside a separate transaction. This will isolate jest workers from each other.
The global setup script (setupFilesAfterEnv
) might look like this:
let pool: DatabasePool;
let connection: Connection;
let server: http.Server;
beforeAll(async () => {
pool = await createPool();
});
afterAll(async () => {
await pool.end();
});
beforeEach(async () => {
connection = await pool.connect(); // This method doesn't exist
await connection.query(sql.unsafe`START TRANSACTION`);
server = await createServer(connection, PORT); // The server will execute all SQL queries inside the same transaction
});
afterEach(async () => {
await new Promise((resolve) => {
server.close(resolve);
});
await connection.query(sql.unsafe`ROLLBACK`);
await connection.release();
});
The connect method allows the connection to be used only inside the callback function:
pool.connect(async (connection) => {
await connection.query(sql.unsafe`START TRANSACTION`);
// ...
await connection.query(sql.unsafe`ROLLBACK`);
});
I need to somehow create a new connection and save it globally in order to run START TRANSACTION
and ROLLBACK
inside the callbacks beforeEach
and afterEach
respectively.
Is it possible?