简体   繁体   中英

How to test NodeJS fs using Mocha/Chai/Sinon?

I want to test the below method from my History class using Mocha/Chai/Sinon, how?

/**
 * Load the history from the history file.
 * @return {this}
 */
load() {
  const file = historyFilePath();

  if (!fs.existsSync(file)) {
    return this;
  }

  const json = fs.readFileSync(file, 'utf8');
  const data = JSON.parse(json);

  this.ary = data;

  return this;
}

The full class is here .

I have noted the answer depending on rewire, but I want to avoid the extra dependency and rewire is also not compatible with babel.

One way, assuming the HistoryFile always has the same structure, is to test if you're getting an object with the correct properties.

For example if your History JSON file would like this

{
    "History": {
        "Name": "Test"
    }
}

You could write your mocha like this:

it('should return a correct object', function() {
  const loadedObject = historyUtil.load();

  expect(loadedObject).to.have.property("History");
  expect(loadedObject.History).to.have.property("Name","Test");
}

This test should fail if:

  1. FS can't find/read the file
  2. JSON.parse doesn't get a parsable string
  3. The HistoryFile schema would change, eg version changes.

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