我的 mocha/chai 断言在实际代码之前运行

My mocha/chai assert runs before the actual code

我正在尝试测试一个函数,但我的断言语句总是在我的实际代码之前运行。我正在测试函数 createAppointment

我的测试:

  describe("Appointments", function() {
    it("should be able to create a new appointment", function(err) {
      let newAppts = [];

      testRequests.forEach(request => {
        createAppointment(testDb, request, function(err, id) {
          if (err) return err;
          newAppts.push(id);
          return id;
        });
      });

      assert.equal(newAppts.length, 5);
    });
  });

我希望 newAppts 的长度为 5,但它 returns 每次都是 0,因为断言在 forEach 完成之前运行。添加回调的最佳方法是什么?

这是一个适合我的测试:

describe("Appointments", function () {
  it("should be able to create 5 new appointments", function (done) {

    // promisify createAppointment, build an array, pass to Promise.all()
    Promise.all(testRequests.map(request => new Promise((resolve, reject) => {
      createAppointment(testDb, request, function (err, id) {
        if (err) reject(err);
        resolve(id);
      });
    })))
    .then(newAppts => {
      // if all Promises resolve, check result
      assert.equal(newAppts.length, 5);
      // and tell mocha we're done
      done();
    })
    .catch(err => {
      // if any one of the Promises fails, we're also done
      done(err);
    });

  });
});

如果您只是想测试 async 代码,return Promise 就足够了。这将简单地检查它是否已解决。
如果您的测试应该检查结果,请不要 return Promise;在调用 assert 检查结果后,使用 it 回调的 done 参数告诉 mocha 异步测试已经完成。