【发布时间】:2020-03-14 05:36:41
【问题描述】:
我正在为我的 Node 应用程序创建一些 mocha 测试。在我的测试中,在检索一些创建的文档之前,我需要先在数据库中创建这些文档。然后我检索它们并对结果进行一些测试。
我注意到的问题是,即使我在第一个 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
});
【问题讨论】:
-
你用的是什么数据库客户端?
-
上面已经添加了详细信息。