完成在模块之前定义的文档之前运行的Mocha测试

时间:2019-11-18 19:24:17

标签: node.js mongodb mocha

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

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

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

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
});

1 个答案:

答案 0 :(得分:1)

您正在混合Promise和异步,这是不必要的。 Nodejs驱动程序supports async/await因此应保持一致。

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

您还没有初始化日期的错误,格式应为:

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

请参见下面的mongodb客户端初始化以及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");
        });
    });
});