Home > other >  mongodb client not connecting in jest test
mongodb client not connecting in jest test

Time:12-14

I am trying to setup an integration test for apollo graphql and need to connect to my mongodb database but this doesnt seem to be working. See the below code:

const MongoClient = require('mongodb').MongoClient
const LOADER_URI = 'mongodb://localhost:27017'

describe('ApolloIntegrationTest', () => {
  test('Test', () => {
    MongoClient.connect(URI, (err, client) => {
      if(err) throw err
      const pulseCore = client.db('pulse-core')
      console.log(pulseCore)
      const books = pulseCore.collection('books')
      console.log(books)
      client.close()
    })
  })
});

When i run the test, i expected to see the console logs printing but nothing prints when the test finishes. Not sure what i am doing wrong here.

CodePudding user response:

You can use beforeAll and afterAll to simplify this.

const MongoClient = require('mongodb').MongoClient;
const LOADER_URI = 'mongodb://localhost:27017'

describe('ApolloIntegrationTest', () => {
  let connection;

  beforeAll(async () => {
    connection = await MongoClient.connect(LOADER_URI);
  });

  afterAll(async () => {
    await connection.close();
  });

  test('Test', async () => {
    const pulseCore = await connection.db('pulse-core');
    console.log(pulseCore);
    const books = pulseCore.collection('books');
    console.log(books);
  });
});
  • Related