mocha 和 chai 测试用例中的承诺失败

Promises in test cases in mocha and chai failing

我正在用 mocha 和 chai 编写一个测试用例来检查文件是否不存在,它将创建文件。以下是测试用例:

context('if the valid message is supplied and file is not present in the app\'s logs folder', () => {
  beforeEach((done) => {
    setTimeout(() => {
      fs.exists(filePath, (exists) => {
        if (exists) {
          fileFound = true;
        } else {
          fileFound = false;
        }
      });
      done();
    }, 100);
  });

  it('should indicate the file is not present in the app\'s log folder', () => {
    expect(fileFound).to.be.false;
  });
  it('should create a new file in the app\'s log folder', () => {
    expect(fileFound).to.be.true;
  });
});

假设文件存在于文件夹中,那么第一个测试用例应该会失败。但问题是,它说的是 expected undefined 是 false,而不是 expected true 是 false。

在这里使用 promises 没有什么意义。您的 API 是基于回调的,因此您应该使用回调测试。

像这样:

it('should exist', (done) => {
  fs.exists(filePath, (exists) => {
    expect(exists).to.be.true;

    done();
  });
});

要记住的一件事(主要与您的问题无关)是 fs.exists is deprecated,您应该使用不同的方法,例如 fs.accessfs.stat:

it('should exist', (done) => {
  fs.access(filePath, (err) => {
    expect(err).to.be.null;

    done();
  });
});

为了解决您的 post edit 问题,这里的问题是您无缘无故地使用 setTimeout 并在之前调用 done fs.exists有机会完成。

解决方案:去掉 setTimeout 并在 fs.exists 回调中调用 done。您还应该将 fileFound 变量的范围限定在有意义的地方:

context('if the valid message is supplied and file is not present in the app\'s logs folder', () => {
  let fileFound;

  beforeEach((done) => {
    fs.exists(filePath, (exists) => {
      fileFound = exists;

      done();
    });
  });

  it('should indicate the file is not present in the app\'s log folder', () => {
    expect(fileFound).to.be.false;
  });
  it('should create a new file in the app\'s log folder', () => {
    expect(fileFound).to.be.true;
  });
});