1

我正在为我的 MongoDB 后端代码使用最新的 ecmascript 语法来学习玩笑测试。我现在正在测试,如果我尝试从空集合中查找文档,测试是否会失败。

光标应该是null结果,因为没有任何返回,这意味着光标是错误的,但是即使我告诉它期待真实并且我不知道为什么,下面的测试仍然通过:

import config from './config'
const mongodb = require('mongodb')

it('sample test', () => {
  mongodb.MongoClient.connect(config.mongodb.url, async (connectErr, db) => {
    expect(db).toBeTruthy()
    let cursor
    try {
      cursor = await db.collection('my_collection').findOne()
      // cursor is null, but test still passes below
      expect(cursor).toBeTruthy()
    } catch (findErr) {
      db.close()
    }
  })
})

另外,这是一种很好的测试方式吗?我在某处读到你不应该在测试中使用 try/catch 块。但这就是您用来处理异步/等待错误的方法。

4

1 回答 1

5

不要将async函数用作回调——因为回调不应该返回承诺;他们的结果将被忽略(并且拒绝不会被处理)。您应该将async函数传递给it它自己,假设 Jest 知道如何处理 Promise。

it('sample test', async () => {
  const db = await mongodb.MongoClient.connect(config.mongodb.url);
  expect(db).toBeTruthy();
  try {
    const cursor = await db.collection('my_collection').findOne();
    expect(cursor).toBeTruthy();
  } finally { // don't `catch` exceptions you want to bubble
    db.close()
  }
});
于 2017-04-13T08:20:53.693 回答