"在所有"之前钩子随机出现在我的测试中

时间:2018-06-12 09:06:51

标签: node.js automated-tests mocha chai

我目前正在运行一个由Express和MongoClient组成的堆栈,其中包含Mocha和Chai进行测试。我正在为我的端点编写测试用例,并且会不时出现随机错误。下面是我写的一套西装的片段:

describe('Recipes with populated database', () => {
    before((done) => {
    var recipe1 = {"search_name": "mikes_mac_and_cheese", "text_friendly_name": "Mikes Mac and Cheese","ingredients": [{"name": "elbow_noodles","text_friendly_name": "elbow noodles","quantity": 12,"measurement": "oz"},{"name": "cheddar_cheese","text_friendly_name": "cheddar cheese","quantity": 6,"measurement": "oz"},{"name": "gouda_cheese","text_friendly_name": "gouda cheese","quantity": 6,"measurement": "oz"},{"name": "milk","text_friendly_name": "milk","quantity": 2,"measurement": "oz"}],"steps": ["Bring water to a boil","Cook noodels until al dente.","Add the milk and cheeses and melt down.","Stir constantly to ensure even coating and serve."],"course": ["dinner","lunch","side"],"prep_time": {"minutes": 15,"hours": 0},"cook_time":{"minutes": 25,"hours": 1},"cuisine": "italian","submitted_by": "User1","searchable": true};

    db.collectionExists('recipes').then((exists) => {
        if (exists) {
            db.getDb().dropCollection('recipes', (err, results) => {
             if (err)
             {
                throw err;
             }
            });
        }

        db.getDb().createCollection('recipes', (err, results) => {
            if (err)
            {
                throw err;
            }
        });

        db.getDb().collection('recipes').insertOne(recipe1, (err, result) => {
            done();
        });
    });
});

collectionExists()方法只接受一个名称并返回一个解析为true/false值的promise。我已经完成了一些调试,它运行得很好。我遇到问题的地方是当我点击我调用createCollection的代码部分时。我收到一个关于集合如何存在的错误,从而导致我的测试失败。这似乎每三次我也会运行我的测试。

所有这一切的目的是确保在开始测试之前我的数据库集合recipes完全是空的,这样我就不会被旧数据或不受控制的环境所困扰。

1 个答案:

答案 0 :(得分:2)

您的.createCollection.insertOne之间存在竞争条件。换句话说,它们同时开始并行。没有办法告诉你先做哪个。

.insert在MongoDB中的工作方式是,如果缺少集合并尝试插入 - 它将创建一个集合。因此,如果首先执行.insertOne,则会创建集合,这就是为什么在尝试already exists时出现createCollection错误的原因。

由于DB调用的异步性质,您必须将后续调用放在prev的回调中。一。这样就不会有并行执行:

before((done) => {
    var recipe1 = {/**/};

    db.collectionExists('recipes')
        .then((exists) => {
            if (exists) {
                // Drop the collection if it exists.
                db.getDb().dropCollection('recipes', (err) => {
                    if (err) {
                        // If there's an error we want to pass it up to before.
                        done(err);
                        return;
                    }

                    // Just insert a first document into a non-existent collection.
                    // It's going to be created.
                    // Notice the done callback.
                    db.getDb().collection('recipes').insertOne(recipe1, done);
                });
            }

            // If there were no such collection - simply insert the first doc to create it.
            // Note that I'm passing before's done callback inside.
            db.getDb().collection('recipes').insertOne(recipe1, done);
        })
        // We don't want to lose the error from this promise always.
        .catch(err => done(err));
});

但是。实际上,每次运行测试时都不需要删除和重新创建集合。您可以简单地.remove before块中的所有对象。所以可能正确的解决方案是:

before((done) => {
    var recipe1 = {/**/};

    const recipes = db.getDb().collection('recipes');

    // Simply wipe out the data
    recipes.remove({}, err => {
        if (err) {
            done(err);
            return;
        }

        recipes.insertOne(recipe1, done);
    });
});