【问题标题】:Unable to use promise returned by Jest beforeAll无法使用 Jest beforeAll 返回的承诺
【发布时间】:2021-05-25 08:52:45
【问题描述】:

我正在尝试使用 mongodb-memory-server、mongodb 和 Jest 为我的 mongodb 查询编写单元测试。我正在尝试从 beforeAll 设置数据库,并希望使用返回到我的测试中的承诺。

这是我使用设置和拆卸部分中提供的 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()
  }
}

还有我的 test.js

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

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

【问题讨论】:

    标签: javascript jestjs


    【解决方案1】:

    你需要将initdb的返回值赋值给某物:

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

    【讨论】:

    • 那行不通,它的作用域是beforeAll函数
    • @thedude 所说的有效,但这与jestjs.io/docs/setup-teardown 中给出的示例相反,我应该能够只使用 initdb 返回的 promise 对象中的变量。知道我该怎么做吗?
    • @thedude 是的,我的错
    猜你喜欢
    • 2020-09-21
    • 1970-01-01
    • 2021-02-20
    • 2017-12-20
    • 1970-01-01
    • 2016-06-15
    • 2019-02-06
    • 2019-09-04
    • 1970-01-01
    相关资源
    最近更新 更多