在Node中进行Mongodb测试

问题描述 投票:1回答:1

我一直在使用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();
  }
 });
});

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

现在,这不起作用,据我所知,这是因为我已经定义了异步和完成。我这样做的原因是,如果我没有定义异步,我需要有一大堆.then和.catches会使代码看起来很糟糕但是如果我不包含那么在最终的done()中阻止,我的测试似乎永远不会成为catch块。

有没有办法在Mocha中编写像这样的测试,这些测试不会使你的代码看起来很可怕?

node.js mongodb mocha
1个回答
1
投票

由于您已经在使用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块中抛出的错误非常重要 - 没有它,即使没有抛出错误,测试仍会通过。

© www.soinside.com 2019 - 2024. All rights reserved.