在Mocha中运行测试之前,Before Block未完成中定义的功能

时间:2019-10-24 18:08:31

标签: node.js mocha chai

我正在Node项目中使用Mocha / Chai创建一些测试。在一个特定的测试中,我需要先将document保存到数据库,然后再检索它,并对找到的文档进行一些检查。

我遇到的问题是it检查在将文档保存到数据库之前正在运行。我不明白为什么会这样,因为我在before()块中进行保存-根据Mocha文档,应在相同的describe块中的测试之前运行,请参见下面的文档:

> With its default "BDD"-style interface, Mocha provides the hooks
> before(), after(), beforeEach(), and afterEach(). These should be used
> to set up preconditions and clean up after your tests.
> 
> describe('hooks', function() {   before(function() {
>     // runs before all tests in this block   });
> 
>   after(function() {
>     // runs after all tests in this block   });
> 
>   beforeEach(function() {
>     // runs before each test in this block   });
> 
>   afterEach(function() {
>     // runs after each test in this block   });
> 
>   // test cases });

为澄清起见,当我第二次(及以后所有)运行测试时,所有检查都通过了,因为到那时,它可以在db中找到该文档。

我在这里想念什么?

这是我的代码:

const assert = require("chai").assert;
const expect = require("chai").expect;
const chai = require("chai");
chai.use(require("chai-datetime"));
const Agenda = require('agenda');

const config = require('./../../configuration');
const url = config.get('MONGO_URL');
const dbName = config.get('MONGO_DATABASE');
const collection = config.get('MONGO_COLLECTION');
const createAgendaJob = require('./../../lib/agenda-jobs/contact-firstname-to-proper-case');

const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);

describe("Contact FirstName to Proper Case", async function () {
  const jobName = "Contact FirstName To Proper Case";
  const testDate = new Date(2019, 01, 01);
  let result;
  let agenda;
  this.timeout(2000);
  before(async function () {
    const connectionOpts = {
      db: {
        address: `${url}/${dbName}`,
        collection
      }
    };

    agenda = new Agenda(connectionOpts);
    await new Promise(resolve => agenda.once('ready', resolve));
    await createAgendaJob(agenda); // Here is where I save the job to the DB
  });
  client.connect(async function (err) {
    assert.equal(null, err);

    const db = await client.db(dbName);

    result = await db.collection("jobs").findOne({
      "name": jobName
    });

    client.close();
  });
  it("should have a property 'name'", function () {
    expect(result).to.have.property("name");
  });
  it("should have a 'name' of 'Contact FirstName To Proper Case'", function () {
    expect(result.name).to.equal("Contact FirstName To Proper Case");
  });
  it("should have a property 'type'", function () {
    expect(result).to.have.property("type");
  });
  it("should have a 'type' of 'normal'", function () {
    expect(result.type).to.equal("normal");
  });
  it("should have a property 'repeatTimezone'", function () {
    expect(result).to.have.property("repeatTimezone");
  });
  it("should have a property 'repeatInterval'", function () {
    expect(result).to.have.property("repeatInterval");
  });
  it("should have a property 'lastModifiedBy'", function () {
    expect(result).to.have.property("lastModifiedBy");
  });
  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);
  });
});

我也尝试过将it检查放在随后的describe()块中,但这也行不通(结果相同-仅在第二次运行测试文件时找到doc):< / p>

const assert = require("chai").assert;
const expect = require("chai").expect;
const chai = require("chai");
chai.use(require("chai-datetime"));
const Agenda = require('agenda');

const config = require('./../../configuration');
const url = config.get('MONGO_URL');
const dbName = config.get('MONGO_DATABASE');
const collection = config.get('MONGO_COLLECTION');
const createAgendaJob = require('./../../lib/agenda-jobs/contact-firstname-to-proper-case');

const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);

describe("Contact FirstName to Proper Case", async function () {
  const jobName = "Contact FirstName To Proper Case";
  const testDate = new Date(2019, 01, 01);
  let result;
  let agenda;
  this.timeout(2000);
  before(async function () {
    const connectionOpts = {
      db: {
        address: `${url}/${dbName}`,
        collection
      }
    };

    agenda = new Agenda(connectionOpts);
    await new Promise(resolve => agenda.once('ready', resolve));
    await createAgendaJob(agenda); // Here is where I save the job to the DB
  });
  client.connect(async function (err) {
    assert.equal(null, err);

    const db = await client.db(dbName);

    result = await db.collection("jobs").findOne({
      "name": jobName
    });

    client.close();
  });
  describe("Check Contact FirstName To ProperCase Found Job", function () {
    it("should have a property 'name'", function () {
      expect(result).to.have.property("name");
    });
    it("should have a 'name' of 'Contact FirstName To Proper Case'", function () {
      expect(result.name).to.equal("Contact FirstName To Proper Case");
    });
    it("should have a property 'type'", function () {
      expect(result).to.have.property("type");
    });
    it("should have a 'type' of 'normal'", function () {
      expect(result.type).to.equal("normal");
    });
    it("should have a property 'repeatTimezone'", function () {
      expect(result).to.have.property("repeatTimezone");
    });
    it("should have a property 'repeatInterval'", function () {
      expect(result).to.have.property("repeatInterval");
    });
    it("should have a property 'lastModifiedBy'", function () {
      expect(result).to.have.property("lastModifiedBy");
    });
    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);
    });
  });
});

1 个答案:

答案 0 :(得分:1)

it尚未完成之前before正在运行,但这早于一切:

    client.connect(async function (err) {
     ...
    });

摩卡(Mocha),在创建测试suide时运行如下代码:

  • 调用传递给describe的每个函数

    • 收集所有itbefore/after*钩子
    • 这就是您的client.connect代码段实际被调用的时间!
  • 然后,在创建整个套件/测试树之后,为每个套件

    • 在*挂接之前适当调用
    • 调用所有it的测试-可能被before/afterAll钩子包围
    • 呼叫after挂钩

每个钩子/测试运行至少在您的情况下等待完成,因为您正确使用了async / await

另外,请注意,这非常腥:

await setTimeout(() => {
  console.log('finished pausing for 5 seconds...');
}, 5000);

这不会等待任何事情,因为setTimeout返回计时器(可能是数字),并且没有明确定义await应该如何处理此数据,因为这是没有保证的。 当然,它不会等待5秒钟。

正确的等待等待看起来如下:

await new Promise(resolve => setTimeout(resolve, 5000))