Reputation: 2301
I'm trying to seed my entire database for all the necessary resources that need to be present to test my API successfully. My tests are in several files.
How can I achieve this such that the database will completely be seeded before one test from any suite runs?
I'm trying to achieve this without using beforeAll
and afterAll
as shown in Jest docs. I want to do the entire seeding before every single one of the test files.
Upvotes: 3
Views: 4059
Reputation: 2301
I ended up figuring this out in the way I originally planned using globalSetup
.
The reason I am using globalSetup
versus handling this in beforeAll
/ afterAll
is that I want it to be run once per npm run test
. I have several *.test.ts
files and don't want to seed and then remove all resources before each one.
I have the following globalSetup
field set in jest.config.ts
globalSetup: "<rootDir>/src/__tests__/setup/setup.api.ts",
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"
// // Global setup file used for tests that will complete once before ALL test suites run
const setup = async () => {
try {
await mongoConnect()
// Sign in the user that will be used for Int / E2E testing
// Also sets the user id for use in seeding logic
await setupTestUser()
// Seed database as needed
// This also handles auto removing stale test resources before seeding
await seedTestDB()
// Grant temporary admin access to test account for unit tests to run
await grantTempAdminAccess(process.env.__TEST_USER_ID__ as string)
await mongoDisconnect()
} catch(err) {
console.log(err)
await mongoDisconnect()
}
}
export default setup
I connect to my database and then set up the test user that will be used for all test requests to endpoints. Everything in my API is behind auth middleware. I then seed that database. Important to note that before I seed the database I remove any resources that might have been seeded previously. Doing this at the beginning instead of the end seemed more reliable. In the end I disconnect from the database.
Upvotes: 3