Paul Paul - 1 month ago 16
Node.js Question

mocha test passing despite apparent stalling on a sync operation

Ok, this is kinda driving me batty. I am trying to run a mocha test on an app I'm writing that's supposed to select and copy a file based on project parameters (a dockerfile). The test is working for other cases, and in fact it's green for this case, except that it shouldn't be.

The test uses

fs.readFileSync
to store the file contents that should be there with the file contents that are actually there, to determine if the right file is copied.

Problem is, there's no file in the location being checked yet (as I haven't written the code to put it there, and I have validated by printing out the directories the test is using and then navigating there myself), but the test passes. Even more strange, as far as I can tell no code executes after the readFileSync operation. But it also doesn't time out...

Here's the test code in question:

it('should create a Dockerfile from ./data/dockerfiles/war.docker', () => {
let projectDocker = path.join(project, 'Dockerfile');
let warDocker = path.join(__dirname, '..', 'data','dockerfiles','war.docker');

select(project, (err, result) => {
let correct = fs.readFileSync(warDocker, 'utf-8');
console.log('projectDocker');
console.log('checking for projectDocker');

let prj = fs.readFileSync(projectDocker, 'utf-8');
console.log('Read file sync for project has completed'); // This line never fires

expect(prj).to.equal(correct);
expect(err).to.not.exist;
expect(result).to.exist;
expect(result).to.have.property('relPath', project);
expect(result).to.have.property('prepared', true);
});
});

Answer

select() looks suspiciously async, in which case your test should be async as well:

it('should create a Dockerfile from ./data/dockerfiles/war.docker', done => {
  ...
  select(project, (err, result) => {
    if (err) return done(err);
    ...
    done();
  });
});

Otherwise you run a big risk of exceptions being swallowed, as @Martin also suggests.

Comments