每次测试前Mocha MongoDB干净收集

时间:2018-11-28 08:28:41

标签: mongodb mocha chai

我正在尝试在每次测试之前清理2个集合。我在编辑测试源文件时使用mocha --watch重新运行测试。首次运行始终会按预期执行,但是连续运行会导致mongodb出现Topology was destroyed错误(通过http请求的结果指示)。

我不确定为什么deleteMany会在连续运行中删除插入的对象。

describe('myCollection1 related tests', () => {
    // myCollection1 documents should refer to a valid myCollection2 document.
    var foo;
    const exampleObject = {name: 'TEST OBJECT', attr1: 'TO'};
    beforeEach(() => {
        return Promise.all([
            mongo.db('mydb').collection('myCollection1').deleteMany({}), // clear collection 1
            mongo.db('mydb').collection('myCollection2').deleteMany({}) // clear collection 2
            .then(() => mongo.db('mydb').collection('myCollection2').insertOne(exampleObject) // and add a sample object
            .then((value) => {
                foo = value.ops[0]; // save this as test specific variable so I can use it in my tests.
                return Promise.resolve();
            })),
        ]);
    });

    it('should create a related object', (done) => {
        chai.request(server)
            .post('/api/v1/foos/')
            .send({ related: foo._id })
            .then((res) => {
                res.should.have.status(200);
                res.body.should.be.an('object').with.all.keys('status', 'errors', 'data');
                done();
            }).catch((err) => {
                done(err);
        });
    });
});

1 个答案:

答案 0 :(得分:0)

我在pipeline = [ {'$project': {'remote.source': 1, 'remote.bytes': 1 }}, {'$unwind': '$users'}, {'$lookup': { 'from': 'user', 'localField': 'users', 'foreignField' : '_id', 'as':'user' }}, {'$match': {'remote.source': {'$exists': True, '$ne': None}}}, {'$project': {'username': '$user.username'}}, {'$group': {'username':'$username','source': '$remote.source', 'count': {'$sum': 1}, 'size': {'$sum': '$remote.bytes'}}} ] for each in Asset.objects().aggregate(*pipeline): print(each) 中发现了您的诺言结构问题。我不确定它是否有意。恐怕是罪魁祸首。我将其修复如下:

beforeEach

希望有帮助