mongodb 客户端在玩笑测试中未连接

mongodb client not connecting in jest test

我正在尝试为 apollo graphql 设置集成测试并且需要连接到我的 mongodb 数据库,但这似乎不起作用。请看下面的代码:

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()
    })
  })
});

当我 运行 测试时,我希望看到控制台日志打印,但测试完成后没有打印任何内容。不确定我在这里做错了什么。

您可以使用 beforeAllafterAll 来简化它。

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);
  });
});