摩卡和柴的测试案例中的承诺失败

时间:2017-11-03 14:43:07

标签: javascript node.js mocha es6-promise chai

我正在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;
  });
});

让我们的日期文件存在于该文件夹中,在这种情况下,第一个测试用例应该失败。但问题是,它表示预期未定义为假,而不是预期是假的。

1 个答案:

答案 0 :(得分:3)

在这里使用承诺毫无意义。您的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();
  });
});

要解决您的帖子编辑问题,此问题在于您无缘无故地使用setTimeout并在done有机会之前致电fs.exists光洁度。

解决方案:摆脱setTimeout并在done回调中调用fs.exists。您还应该将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;
  });
});