mocha didn't work when using fs.readFile or fs.writeFile

Created on 9 May 2015  路  4Comments  路  Source: mochajs/mocha

mocha 2.2.4
I tried assert, expect.js, and should.js. All the three assert modules didn't work in mocha when they were called in fs.readFile or fs.writeFile. My test file is in this gist post.

Most helpful comment

PTAL on testing asynchronous code example and let me know if there's any problems.
Thanks.

Update:
based on your gist, this example should be something like that:

describe('Test on I/O', function() {
  it('write test', function(done) {
    fs.writeFile('./text.txt', "Hello Node.js" + os.EOL, function(err) {
      if (err) {
        throw "Unable to read file";
      }
      expect(3).to.equal(4); // Should fail
      done();
    });
  });

  it('read test', function(done) {
    fs.readFile('./file.txt', function(err, data) {
      if (err) {
        throw "Unable to read file";
      }
      expect(3).to.equal(4); 
      done();
    });
  });
});

All 4 comments

PTAL on testing asynchronous code example and let me know if there's any problems.
Thanks.

Update:
based on your gist, this example should be something like that:

describe('Test on I/O', function() {
  it('write test', function(done) {
    fs.writeFile('./text.txt', "Hello Node.js" + os.EOL, function(err) {
      if (err) {
        throw "Unable to read file";
      }
      expect(3).to.equal(4); // Should fail
      done();
    });
  });

  it('read test', function(done) {
    fs.readFile('./file.txt', function(err, data) {
      if (err) {
        throw "Unable to read file";
      }
      expect(3).to.equal(4); 
      done();
    });
  });
});

Add done() function solved the problem. Thanks a lot.

@a8m how do i test it without failing the test ? i mean i want to pass my test instead of failing it

I would do it like this...

var assert = require('assert');
var fs = require('fs');
var os = require('os');
var path = require('path');
var util = require('util');

describe('File I/O', function() {
  var pathname;
  var content = "Howdy";

  before(function() {
    var filename = util.format('io-testfile-mocha-%s.txt', process.pid);
    pathname = path.join(os.tmpdir(), filename);
  });

  it('should write to file', function(done) {
    fs.writeFile(pathname, content, function(err) {
      if (err) {
        return done(err);
      }
      done();
    });
  });

  it('should read from file', function(done) {
    fs.readFile(pathname, function(err, data) {
      if (err) {
        return done(err);
      }
      assert.strictEqual(data, content);
      done();
    });
  });

  after(function() {
    fs.unlinkSync(pathname);
  });
});
Was this page helpful?
0 / 5 - 0 ratings