Mongodb 在 Node 中测试

Mongodb testing in Node

我一直在使用 Mocha 在 Node 中进行测试,因为它似乎是大多数人使用的。我还使用 MongoDB 来存储我的数据,因为我的服务器是一个简单的 API 服务器,我几乎所有的方法都只是普通的数据库查询,我正在尝试使用 Mocha 进行测试。 现在我面临的问题是(除了通常很难测试异步函数这一事实之外)我似乎找不到合适的方法来测试 mongoDB 异常。

  it('Should not create account', async (done) => {
   try {
    await createAccountDB(user);
    await createAccountDB(user);
  } catch (err) {
    assert.notEqual(err, null);
    console.log(err);
  }
  finally {
    done();
  }
 });
});

我在这里尝试的是为用户创建一个帐户(基本上只是将对象保存到数据库),然后再次创建相同的帐户,这应该会导致重复密钥错误。

现在,这不起作用,据我所知,这是因为我同时定义了 async 和 done。我这样做的原因是,如果我不定义异步,我将需要一大堆 .then 和 .catches,这会使代码看起来很糟糕,但如果我不在 finally 中包含 then done()块,我的测试似乎从来没有进入 catch 块。

有没有什么方法可以在 Mocha 中编写这样的测试而不会使您的代码看起来非常糟糕?

由于您已经在使用 async/await 模型,因此您不一定需要测试用例的 done 回调。当您有不止一种指示测试完成的方法时,某些版本的 mocha 会警告您。试试这个:

it('should not create an account', async function() {
   try {
    await createAccountDB(user);
    await createAccountDB(user);
    throw new Error('Did not reject a duplicate account');
  } catch (err) {
    assert.notEqual(err, null);
    // any other assertions here
  }
});

try/catch 块中抛出的错误 非常 重要 - 没有它,即使没有抛出错误,测试仍然会通过。