简体   繁体   中英

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. 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.

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 :

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.

The solution: get rid of the setTimeout and call done inside the fs.exists callback. You should also scope your fileFound variable at a place where it makes sense:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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