After some thought, I eventually found a solution to my problem using globalSetup
.
I opted for using globalSetup
over managing it in beforeAll
/ afterAll
because I wanted it to run only once per npm run test
. With multiple *.test.ts
files, I didn't want to seed and delete resources before each individual test.
In my jest.config.ts
file, I have set the following value for the globalSetup
field:
globalSetup: "<rootDir>/src/__tests__/setup/setup.api.ts",
The contents of setup.api.ts
:
import 'tsconfig-paths/register';
import { seedTestDB } from "./setup.db"
import { setupTestUser } from "./testHelpers"
import { mongoConnect, mongoDisconnect } from "../../server/services/mongo"
import User from "../../models/User"
const setup = async () => {
try {
await mongoConnect()
await setupTestUser()
await seedTestDB()
await grantTempAdminAccess(process.env.__TEST_USER_ID__ as string)
await mongoDisconnect()
} catch(err) {
console.log(err)
await mongoDisconnect()
}
}
export default setup
The process involves connecting to the database, setting up a test user that will be used for all requests to API endpoints, and seeding the database. It's worth mentioning that I remove any previously seeded resources before initiating the seeding process. This approach seemed more reliable to me. Finally, I disconnect from the database.