完成在模块之前定义的文档之前运行的Mocha测试 [英] Mocha Tests Running Before Docs Defined in Before Block Are Done

查看:70
本文介绍了完成在模块之前定义的文档之前运行的Mocha测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的Node应用程序创建一些摩卡测试.在我的测试中,在检索创建的某些文档之前,我需要首先在数据库中创建这些文档.然后,我检索它们并对结果进行一些测试.

I am creating some mocha tests for my Node app. In my test, before retrieving some docs that are created, I need to first create those docs in the database. Then I retrieve them and run some tests on the results.

我注意到的问题是,即使我已经在第一个before()块中包含了创建文档所需要运行的功能,并且即使我正在等待文档创建功能的结果,我的测试在文档创建完成之前运行.似乎before()块并没有完全按照我的想法做.

The problem I'm noticing is that even though I've included the function that needs to run to create the docs in the first before() block, and even though I'm awaiting the result of the doc creation function, my tests run BEFORE the docs are finished being created. It seems the before() block doesn't do quite what I think it does.

我该如何纠正这一问题,以确保在运行测试检查之前完成文档的创建?

How can I rectify this to ensure the doc creation has finished BEFORE the test checks run?

const seedJobs = require('./seeder').seedJobs;

const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(`${url}${dbName}${auth}`);

describe("Seeding Script", async function () {
  const testDate = new Date(2019, 01, 01);
  let db;
  before(async function () {
    await seedJobs(); // This is the function that creates the docs in the db
    return new Promise((resolve, reject) => {
      client.connect(async function (err) {
        assert.equal(null, err);
        if (err) return reject(err);
        try {
          db = await client.db(dbName);
        } catch (error) {
          return reject(error);
        }
        return resolve(db);
      });
    });
  });
  // Now I retrieve the created doc and run checks on it
  describe("Check VBR Code Update", async function () {
    let result;
    const jobName = 'VBR Code Update';
    this.timeout(2000);
    before(async function () {
      result = await db.collection(collection).findOne({
        name: jobName
      });
    });
    it("should have a property 'name'", async function () {
      expect(result).to.have.property("name");
    });
    it("should have a 'name' of 'VBR Code Update'", async function ()    
      expect(result.name).to.equal(jobName);
    });
    it("should have a property 'nextRunAt'", function () {
      expect(result).to.have.property("nextRunAt");
    });
    it("should return a date for the 'nextRunAt' property", function () {
      assert.typeOf(result.nextRunAt, "date");
    });
    it("should 'nextRunAt' to be a date after test date", function () {
      expect(result.nextRunAt).to.afterDate(testDate);
    });
  });
  // Other tests
});

推荐答案

您正在将Promise和异步混合在一起,而这是不必要的. Nodejs驱动程序支持异步/等待保持一致.

You are mixing promises and async together which is not needed. The Nodejs driver supports async/await so rather keep it consistent.

我看不到seedJobs函数,但假定它按预期工作.我建议您按照以下示例更新before函数.

I cannot see the seedJobs function but assume it works as expected. I suggest you update the before function as per the example below.

您在初始化日期时也出错,格式应为:

You also have an error initializing the date, the format should be:

const testDate = new Date(2019, 1, 1);

请参见下面的mongodb客户端初始化以及await的使用:

See the below init of mongodb client and use of await:

const mongodb = require('mongodb');
const chai = require('chai');
const expect = chai.expect;

const config = {
    db: {
        url: 'mongodb://localhost:27017',
        database: 'showcase'
    }
};

describe("Seeding Script",  function () {
    const testDate = new Date(2019, 1, 1);

    let db;

    seedJobs = async () => {
        const collections = await db.collections();
        if (collections.map(c => c.s.namespace.collection).includes('tests')) {
            await db.collection('tests').drop();
        }

        let bulk = db.collection('tests').initializeUnorderedBulkOp();

        const count = 5000000;
        for (let i = 0; i < count; i++) {
            bulk.insert( { name: `name ${i}`} );
        }

        let result = await bulk.execute();
        expect(result).to.have.property("nInserted").and.to.eq(count);

        result = await db.collection('tests').insertOne({
            name: 'VBR Code Update'
        });

        expect(result).to.have.property("insertedCount").and.to.eq(1);
    };

    before(async function () {
         this.timeout(60000);

        const connection = await mongodb.MongoClient.connect(config.db.url, {useNewUrlParser: true, useUnifiedTopology: true});

        db = connection.db(config.db.database);

        await seedJobs();
    });

    // Now I retrieve the created doc and run checks on it
    describe("Check VBR Code Update", async function () {
        let result;
        const jobName = 'VBR Code Update';
        this.timeout(2000);

        before(async function () {
            result = await db.collection('tests').findOne({
                name: jobName
            });
        });

        it("should have a property 'name'", async function () {
            expect(result).to.have.property("name");
        });
    });
});

这篇关于完成在模块之前定义的文档之前运行的Mocha测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆