node.js - 将await/async 与mocha、chai 一起使用

标签 node.js express mocha.js chai

我对 Node 和 Express 还很陌生。 并一直尝试使用 mocha、chai 和 chai-http 编写测试代码。 这是部分源代码。

const mongoose = require('mongoose'),
  User = require('../../models/user');

const mongoUrl = 'mongodb://xxxxxxxxxxx';

describe('/test', function() {
  before('connect', function() {
    return mongoose.createConnection(mongoUrl);
  });

  beforeEach(async function(done) {
    try {
      await User.remove({}); // <-- This doesn't work
      chai.request('http://localhost:3000')
        .post('/api/test')
        .send(something)
        .end((err, res) => {
          if (err) return done(err);
          done();
        });
    } catch (error) {
      done(error);
    }
  });
});

我在“npm test”(nyc mocha --timeout 10000 test/**/*.js) 中收到以下错误。

Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

我从日志中确认数据库连接工作正常。 似乎我收到了等待 User.remove({}) 的超时错误。 我还尝试了不同的方法,例如 User.save() 但是,我遇到了同样的错误。 我需要对数据库模型和连接做一些特殊的事情吗?

最佳答案

这一切都很简单。

为避免该错误,您不得在 Mocha 中同时使用 doneasync/await。使用 async/await 并删除 done 作为函数参数和 done() 调用。或者使用done。然后删除async/await。请参阅下面每种情况的示例测试。

try/catchasync/await 一起使用,就像通常将其与同步代码一起使用一样。

以下是最基本的 Mocha 测试,使用 async/awaitdone 方法测试相同的基本 HTTP 服务器端点。

这是async/await方法。

it('with async/await', async function() {
    const res = await chai.request(server)
        .get('/')
        .send();
    assert.equal(res.status, 200);
});

这是完成方法。

it('with done & callbacks', (done) => {
    chai.request(server)
        .get('/')
        .end((err, res) => {
            assert.equal(res.status, 200);
            done();
        });
});

请参阅full test file snippet .

对于工作示例,另外旋转 basic Express server作为 src/app.js 中的测试对应项。

参见Chai HTTP插件文档,了解有关请求测试可以做什么的更多信息。

就是这样。

关于node.js - 将await/async 与mocha、chai 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51675305/

相关文章:

node.js - 我应该同时使用 Nginx 和 HAProxy 作为生产 Node 应用程序吗?

node.js - HTTPS 与 NodeJS swagger-express-mw npm 包

node.js - 异步 Mocha 测试(使用 Chai 断言库)应该失败,但被标记为通过

node.js - 使用 promise 解析/拒绝对 Mongoose 验证进行单元测试

javascript - 解释connect session中的length和clear session store方法

node.js - MapReduce 中的 MongoDB 动态变量

javascript - 如何在 index.html 的 assets 文件夹中设置文件

node.js - 从子进程到 API 的请求导致 ECONNRESET

node.js - 如何让 Mocha 识别单元测试

node.js - 全局 Sequelize Store 查询值