本文介绍了在Mocha,Chai中使用Await / Async的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对节点表达很陌生。
并且一直在尝试使用mocha,chai和chai-http编写测试代码。
这是源代码的一部分。

I'm quite new to node and express.And have been trying to write test code using mocha, chai and chai-http.Here's the part of source code.

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)。

And I get the following error with "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()
但是,我遇到了同样的错误。
我需要对数据库模型和连接做一些特别的事情吗?

I confirmed the database connection works properly from log.And seems I get the timeout error with await User.remove({}).I've also tried different methods such as a User.save()But, I got the same error.Do I need to do something special with database model and connection?

推荐答案

,但没有找到获取任何问题的方法与Mocha / Chai合作的猫鼬的承诺。

I had the same problem and have not found a way to get any promises that involve mongoose working with Mocha/Chai.

可能会帮助您完成我所做的工作,并将您的猫鼬代码放入脚本中,以便您可以使用 node< scriptfile>运行它。 js 。您可以使用它来确认它本身是否可以正常工作。在我的测试中,猫鼬手术不到一秒钟就完成了。您还可以从另一个文件(与测试无关的文件)中调用该文件,以确认文件是否正确执行并返回承诺。您可以从我的中看到如何确保正确关闭数据库。部分示例:

What may help you is doing what I did and putting your mongoose code in a script so you can run it with node <scriptfile>.js. You can use that to confirm it's working properly by itself. In my test, the mongoose operation finished in less than a second. You can also call that file from another (non-test related) to confirm it executes properly and returns a promise. You can see from my example how to make sure you close db properly. Partial example:

  ...
  db.close();

  return new Promise((resolve) => {
    db.on('disconnected', () => {
      console.log('***************************************Mongoose CONNECTION TERMINATED');
      resolve('user ready');
    });
  });
  ...

通过查看以下问题,您可能还会发现一些线索和。

You may also find some clues by looking at the following issues here and here.

我在浪费大量时间试图弄清楚这种疯狂行为后所做的工作是执行我的猫鼬需要一条路线。我将需要使用的每个请求包装在额外的 chai.request ... end 块中,或使用异步。示例:

The work around that I did after wasting too much time trying to figure out this crazy behavior was to perform my mongoose needs in a route. I wrap each request that needs to use it in the end block of the extra chai.request... or use async. Example:

describe('something', () => {
  it('should do something and change it back', async () => {
    try {
      // change user password
      let re1 = await chai.request(app)
        .post('/users/edit')
        .set('authorization', `Bearer ${token}`)
        .send({
          username: '[email protected]',
          password: 'password6',
        });
      expect(re1.statusCode).to.equal(200);

      // change password back since before hook not working
      let re2 = await chai.request(app)
        .post('/users/edit')
        .set('authorization', `Bearer ${token}`)
        .send({
          username: '[email protected]',
          password: 'password6',
          passwordNew: 'password',
          passwordConfirm: 'password',
        });
      expect(re2.statusCode).to.equal(200);
    } catch (error) {
      // error stuff here
    }
  });

请注意,使用 try / catch 语法以上将导致通常无法通过测试的测试,结果将被捕获在catch块中。如果要避免这种情况,只需删除 try / catch

Note that using the try/catch syntax above will cause test that should normally fail to show passing and the results will be caught in the catch block. If you want to avoid that, just remove the try/catch.

这篇关于在Mocha,Chai中使用Await / Async的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:57