简体   繁体   English

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

[英]Promises in test cases in mocha and chai failing

I am writing a test case in mocha and chai to check if the file is not present it will create the file. 我正在mocha和chai中编写测试用例,以检查文件是否不存在,它将创建文件。 Following is the test case : 以下是测试案例:

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;
  });
});

Let's day file is present in the folder, in that case first test case should fail. 文件夹中存在文件,在这种情况下,第一个测试用例应该失败。 But the problem is, it is saying expected undefined to be false, rather than expected true to be false. 但是问题是,这是说期望未定义为假,而不是期望为真。

There's very little point in using promises here. 在这里使用诺言毫无意义。 Your API is callback-based, so you should use a callback test. 您的API是基于回调的,因此您应该使用回调测试。

Like this: 像这样:

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

    done();
  });
});

One thing to bear in mind, mostly unrelated to your issue, is that fs.exists is deprecated and you should use a different method like fs.access or fs.stat : 要记住的一件事是, 建议使用fs.exists ,而大多数情况与您的问题无关,您应该使用fs.accessfs.stat类的其他方法:

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

    done();
  });
});

To address your post edit question, the problem here is that you are using setTimeout for no reason and calling done before fs.exists has a chance to finish. 为了解决您的帖子编辑问题,这里的问题是您无缘无故地使用setTimeout ,并且在fs.exists有机会done之前调用完成。

The solution: get rid of the setTimeout and call done inside the fs.exists callback. 解决办法:摆脱了setTimeout和呼叫done内部fs.exists回调。 You should also scope your fileFound variable at a place where it makes sense: 您还应该在fileFound的位置作用域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;
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM