【问题标题】:Clearing collection before testing with Mocha在使用 Mocha 测试之前清除集合
【发布时间】:2018-10-29 21:53:28
【问题描述】:

我正在使用 Mocha、Chai 和 Mongoose 为我的 Node.js 应用程序编写单元测试。如果集合为空(根据需要),测试本身会起作用,但我在测试之前无法清除集合。

let mongoose = require("mongoose");
let Subject = require('../Subject/subject');

//Require the dev-dependencies
let chai = require('chai');
let chaiHttp = require('chai-http');
// let server = require('../server');
let server = "http://localhost:3000"
let should = chai.should();

chai.use(chaiHttp);

describe('subjects', () => {
  before((done) => { //Before each test, empty the database
    Subject.remove({})
    done();         
  });

  describe('/GET subject', () => {
    // working test
  });

  describe('/POST subject', () => {
    // working test
  });

  describe('/GET subject', () => {
    // working test
  });
});

我也尝试过

Subject.deleteMany({}, (err) => console.log(err));

Subject.find({}, (subject)=>{
   subject.remove({}).exec()
})

在前块内无济于事。为了以防万一,我也尝试了在 before 块之外的删除。如果我 console.log(Subject.remove({})) 我得到了 Subject 对象,那么它就可以访问它,只是实际上并没有用它做任何永久性的事情。

我已经做了几个小时了,还没有更接近弄清楚,所以感谢所有帮助。

【问题讨论】:

    标签: node.js unit-testing mongoose mocha.js chai


    【解决方案1】:

    由于 Mocha 和 Mognoose 都支持异步块的承诺,它们可以无缝使用,而不是直接调用 done。在这种情况下,应返回一个承诺:

      before(() => Subject.remove({}));
    

    【讨论】:

    • 尝试这样做最终会导致超时错误。我最初遇到这个问题是由于错误地放置了 done() 调用。
    • 可以理解为什么错误地放置done 会导致问题,但是remove 在没有回调的情况下返回thenable,它应该可以工作。这就是在 Mocha 中的做法,mochajs.org/#working-with-promises。在这种情况下应该没有doneSubject.remove({}).exec() 可能会起作用,但我希望它在没有 exec 的情况下也能起作用。
    【解决方案2】:

    尝试像这样等待删除调用的回调

    before((done) => { //Before each test, empty the database
     Subject.remove({}, done);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-22
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      相关资源
      最近更新 更多