如何使用Mocha / Chai / Sinon测试NodeJS fs?

时间:2017-05-09 19:12:44

标签: node.js mocha sinon

我想使用Mocha / Chai / Sinon从我的History类测试下面的方法,怎么做?

/**
 * 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;
}

完整的课程为here

我注意到answer取决于重新布线,但我希望避免额外的依赖,重新布线也与babel不兼容。

1 个答案:

答案 0 :(得分:0)

一种方法,假设HistoryFile总是具有相同的结构,就是测试你是否正在获得具有正确属性的对象。

例如,如果您的History JSON文件需要此

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

你可以像这样编写你的摩卡:

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

如果出现以下情况,此测试将失败:

  1. FS无法找到/读取文件
  2. JSON.parse没有获得可解析的字符串
  3. HistoryFile架构会改变,例如版本更改。
相关问题