jest-mongodb
jest-mongodb copied to clipboard
Connecting in globalSetup doesn't work
Hi, I have multiple test files that use Mongo. I would like to connect only once (in the globalSetup.ts), and disconnect only once, after every test is done, on globalTeardown.ts.
I tried following the steps from https://github.com/shelfio/jest-mongodb/issues/212
But it doesn't seem to work.
This is my globalSetup.ts. It seems to be working fine, the MONGO_URL is always set.
./server/tests/__scripts__/globalSetup.ts
// @ts-nocheck
import mongoose from 'mongoose'
import mongoSetup from '@shelf/jest-mongodb/setup'
import dotenv from 'dotenv'
dotenv.config()
module.exports = async () => {
await mongoSetup()
console.log('env is: ', process.env.MONGO_URL)
await mongoose.connect(process.env.MONGO_URL as string, {
dbName: 'jest',
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
})
}
However, in all of my tests, Mongo is just unresponsive. Jest throws the "Exceeded timeout of 5000ms for a hook" error.
It does work, however, if I connect inside the test file using beforeAll:
./server/tests/repositories/notificationRepository.test.ts
beforeAll(async () => {
await mongoose.connect(process.env.MONGO_URL as string, {
dbName: 'jest',
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
})
})
This is my config:
./server/tests/jest.base.config.js
const merge = require('merge')
const tsJestPreset = require('ts-jest/jest-preset')
const mongoDbMemoryPreset = require('@shelf/jest-mongodb/jest-preset')
module.exports = merge(tsJestPreset, mongoDbMemoryPreset, {
// testEnvironment: 'node',
setupFilesAfterEnv: ['./jest.setup.js'],
modulePaths: ['../'],
maxWorkers: 1,
globalSetup: './__scripts__/globalSetup.ts',
globalTeardown: './__scripts__/globalTeardown.ts',
globals: {
'ts-jest': {
tsConfig: './tsconfig.json'
}
}
})
Am I missing something obvious? Is there a way I can connect to Mongo inside globalSetup and use the connection throughout my test files?
Thanks!
I am having this same issue.