Javascript 无法使用之前由Jest返回的承诺

Javascript 无法使用之前由Jest返回的承诺,javascript,jestjs,Javascript,Jestjs,我试图使用mongodb内存服务器、mongodb和Jest为我的mongodb查询编写单元测试。我试图从以前开始设置db,并希望使用返回到测试中的承诺 以下是我的代码,我使用安装和拆卸部分中提供的Jest文档开发: dbOperations.js const { MongoMemoryServer } = require('mongodb-memory-server') const MongoClient = require('mongodb').MongoClient const test

我试图使用mongodb内存服务器、mongodb和Jest为我的mongodb查询编写单元测试。我试图从以前开始设置db,并希望使用返回到测试中的承诺

以下是我的代码,我使用安装和拆卸部分中提供的Jest文档开发:

dbOperations.js

const { MongoMemoryServer } = require('mongodb-memory-server')
const MongoClient = require('mongodb').MongoClient

const testDocument = {
  "name" : "test"
}
let client = null
let mongoServer = null

module.exports.initdb = async () => {

  mongoServer = new MongoMemoryServer()
  const mongoUri = await mongoServer.getUri()
  console.log("init db -----------------")
  try {
        client = await MongoClient.connect(mongoUri, {
          useUnifiedTopology: true,
        })
      const test_db = await client.db(await mongoServer.getDbName())  //generates random DB name.
      const test_collection = await test_db.collection("test")
      console.log("in function------", await test_db.stats())  // i can see these in output
      await test_collection.insertOne(testDocument) // load test data
      return {
        test_db,
        test_collection
      }
  } 
  catch(e) {
      console.log("Setup Error", e)
  }
}

module.exports.teardown = () => {
  if (client) {
      console.log("closing mongo client")
     client.close()
  }
  if (mongoServer) {
      console.log("closing mongo server")
     mongoServer.stop()
  }
}
const {initdb, teardown}  = require('../testUtils/dbOperations')

describe('MongoDB Test Suite', () => {

    beforeAll ( () => {
        return initdb()
    })
    
    afterAll ( () => {
        return teardown()
    })

    test('test connection and document setup ', async () => {
        let docCount = await test_collection.countDocuments({})
        expect(test_db).toBeDefined()
        expect(docCount).toBe(1);
    })
})
和my test.js

const { MongoMemoryServer } = require('mongodb-memory-server')
const MongoClient = require('mongodb').MongoClient

const testDocument = {
  "name" : "test"
}
let client = null
let mongoServer = null

module.exports.initdb = async () => {

  mongoServer = new MongoMemoryServer()
  const mongoUri = await mongoServer.getUri()
  console.log("init db -----------------")
  try {
        client = await MongoClient.connect(mongoUri, {
          useUnifiedTopology: true,
        })
      const test_db = await client.db(await mongoServer.getDbName())  //generates random DB name.
      const test_collection = await test_db.collection("test")
      console.log("in function------", await test_db.stats())  // i can see these in output
      await test_collection.insertOne(testDocument) // load test data
      return {
        test_db,
        test_collection
      }
  } 
  catch(e) {
      console.log("Setup Error", e)
  }
}

module.exports.teardown = () => {
  if (client) {
      console.log("closing mongo client")
     client.close()
  }
  if (mongoServer) {
      console.log("closing mongo server")
     mongoServer.stop()
  }
}
const {initdb, teardown}  = require('../testUtils/dbOperations')

describe('MongoDB Test Suite', () => {

    beforeAll ( () => {
        return initdb()
    })
    
    afterAll ( () => {
        return teardown()
    })

    test('test connection and document setup ', async () => {
        let docCount = await test_collection.countDocuments({})
        expect(test_db).toBeDefined()
        expect(docCount).toBe(1);
    })
})
和我的控制台输出:

  MongoDB Test Suite
    ✕ test connection and document setup  (3 ms)

  ● MongoDB Test Suite › test connection and document setup 

    ReferenceError: test_collection is not defined

      15 |
      16 |     test('test connection and document setup ', async () => {
    > 17 |         let docCount = await test_collection.countDocuments({})
         |                        ^
      18 |         expect(test_db).toBeDefined()
      19 |         expect(docCount).toBe(1);
      20 |     })

      at Object.test (tests/unit-tests/test.js:17:24)

  console.log
    init db -----------------

      at Object.<anonymous>.module.exports.initdb (tests/testUtils/dbOperations.js:14:11)

  console.log
    in function------ { db: '5129a396-09f4-43ad-8ceb-b843932a3956',
      collections: 0,
      views: 0,
      objects: 0,
      avgObjSize: 0,
      dataSize: 0,
      storageSize: 0,
      numExtents: 0,
      indexes: 0,
      indexSize: 0,
      fileSize: 0,
      ok: 1 }

      at Object.<anonymous>.module.exports.initdb (tests/testUtils/dbOperations.js:21:15)

  console.log
    Setup Error ReferenceError: test_db is not defined
        at Object.<anonymous>.module.exports.initdb (/Users/souparno/Code/aws-lambdas/tests/testUtils/dbOperations.js:24:9)
        at process._tickCallback (internal/process/next_tick.js:68:7)

      at Object.<anonymous>.module.exports.initdb (tests/testUtils/dbOperations.js:29:15)

  console.log
    closing mongo client

      at teardown (tests/testUtils/dbOperations.js:35:15)

  console.log
    closing mongo server

      at teardown (tests/testUtils/dbOperations.js:39:15)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.971 s, estimated 1 s
MongoDB测试套件
✕ 测试连接和文档设置(3毫秒)
● MongoDB测试套件›测试连接和文档设置
ReferenceError:未定义测试集合
15 |
16 |测试('测试连接和文档设置',异步()=>{
>17 | let docCount=wait test_collection.countDocuments({})
|                        ^
18 | expect(test_db).toBeDefined()
19 | expect(docCount)。toBe(1);
20 |     })
在Object.test(tests/unittests/test.js:17:24)
console.log
初始化数据库-----------------
在Object..module.exports.initdb(tests/testUtils/dbOperations.js:14:11)
console.log
在函数---{db:'5129a396-09f4-43ad-8ceb-b843932a3956'中,
收藏:0,
浏览次数:0,
对象:0,
avgObjSize:0,
数据大小:0,
存储大小:0,
数值范围:0,
索引:0,
索引大小:0,
文件大小:0,
ok:1}
在Object..module.exports.initdb(tests/testUtils/dbOperations.js:21:15)
console.log
设置错误引用错误:未定义测试数据库
在Object..module.exports.initdb(/Users/souparno/Code/aws lambdas/tests/testUtils/dbOperations.js:24:9)
在进程中。_tick回调(内部/process/next_tick.js:68:7)
在Object..module.exports.initdb(tests/testUtils/dbOperations.js:29:15)
console.log
关闭mongo客户端
拆卸时(tests/testUtils/dbOperations.js:35:15)
console.log
关闭mongo服务器
拆卸时(tests/testUtils/dbOperations.js:39:15)
测试套件:1个失败,共1个
测试:1次失败,共1次
快照:共0个
时间:0.971s,估计1s

如果我把所有代码放在一个模块中,一切都正常工作。不知何故,当在新模块中拆分设置函数时,我无法利用在beforeAll块中调用的initdb返回的承诺。

您需要将
initdb
的返回值分配给以下内容:

 describe('MongoDB Test Suite', () => {
     let test_collection
     beforeAll ( async () => {
        const result = await initdb()
        test_collection = result.test_collection
     })
...

您需要将
initdb
的返回值分配给以下内容:

 describe('MongoDB Test Suite', () => {
     let test_collection
     beforeAll ( async () => {
        const result = await initdb()
        test_collection = result.test_collection
     })
...

这是行不通的,它将被限定为@thedude所说有效的
函数之前的
,但这与中给出的示例相反,我应该能够只使用initdb返回的promise对象中的变量。你知道我该怎么做吗?@thedude是的,我的坏消息是不起作用的,它的作用域将是@thedude所说的起作用之前的
函数,但这与中给出的示例相反,我应该能够只使用initdb返回的promise对象中的变量。“你知道我怎样才能做到吗?”德德是我的错