Skip to content

Commit 22724d5

Browse files
test: inform devs when db connection not established (freeCodeCamp#60539)
1 parent 5cb96cf commit 22724d5

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

api/jest.utils.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,19 @@ const indexData: IndexData[] = [
155155
}
156156
];
157157

158+
export async function checkCanConnectToDb(
159+
prisma: FastifyTestInstance['prisma']
160+
): Promise<void> {
161+
const countP = prisma.user.count();
162+
const delayedRejection = new Promise((_resolve, reject) =>
163+
setTimeout(
164+
() => reject(Error('unable to connect to Mongodb (timeout)')),
165+
1000
166+
)
167+
);
168+
await Promise.race([countP, delayedRejection]);
169+
}
170+
158171
export function setupServer(): void {
159172
let fastify: FastifyTestInstance;
160173
beforeAll(async () => {
@@ -165,6 +178,8 @@ export function setupServer(): void {
165178
fastify = await build(buildOptions);
166179
await fastify.ready();
167180

181+
await checkCanConnectToDb(fastify.prisma);
182+
168183
// Prisma does not support TTL indexes in the schema yet, so, to avoid
169184
// conflicts with the TTL index in the sessions collection, we need to
170185
// create it manually (before interacting with the db in any way). Also,

api/src/plugins/auth-dev.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import Fastify, { FastifyInstance } from 'fastify';
22

3-
import { defaultUserEmail } from '../../jest.utils';
3+
import { checkCanConnectToDb, defaultUserEmail } from '../../jest.utils';
44
import { HOME_LOCATION } from '../utils/env';
55
import { devAuth } from '../plugins/auth-dev';
66
import prismaPlugin from '../db/prisma';
@@ -19,6 +19,7 @@ describe('dev login', () => {
1919
await fastify.register(auth);
2020
await fastify.register(devAuth);
2121
await fastify.register(prismaPlugin);
22+
await checkCanConnectToDb(fastify.prisma);
2223
});
2324

2425
beforeEach(async () => {

api/src/routes/helpers/auth-helpers.test.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@ import Fastify, { FastifyInstance } from 'fastify';
22

33
import db from '../../db/prisma';
44
import { createUserInput } from '../../utils/create-user';
5+
import { checkCanConnectToDb } from '../../../jest.utils';
56
import { findOrCreateUser } from './auth-helpers';
67

78
const captureException = jest.fn();
89

910
async function setupServer() {
1011
const fastify = Fastify();
1112
await fastify.register(db);
13+
await checkCanConnectToDb(fastify.prisma);
1214
// @ts-expect-error we're mocking the Sentry plugin
1315
fastify.Sentry = { captureException };
1416
return fastify;

0 commit comments

Comments
 (0)