Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connecting in globalSetup doesn't work #297

Open
kibebr opened this issue Sep 2, 2021 · 1 comment
Open

Connecting in globalSetup doesn't work #297

kibebr opened this issue Sep 2, 2021 · 1 comment

Comments

@kibebr
Copy link

kibebr commented Sep 2, 2021

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 #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!

@Babatunde50
Copy link

I am having this same issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants