Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使用Mocha/Chai/Sinon测试NodeJS fs?_Node.js_Mocha.js_Sinon - Fatal编程技术网

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

Node.js 如何使用Mocha/Chai/Sinon测试NodeJS fs?,node.js,mocha.js,sinon,Node.js,Mocha.js,Sinon,我想在我的历史课上用摩卡/柴/西农测试以下方法,如何 /** * 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

我想在我的历史课上用摩卡/柴/西农测试以下方法,如何

/**
 * 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;
}
全班都是


我注意到依赖于rewire,但我想避免额外的依赖性,rewire也与babel不兼容。

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

例如,如果您的历史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");
}
如果出现以下情况,该测试应失败:

  • FS无法找到/读取该文件
  • JSON.parse无法获取可解析字符串
  • HistoryFile架构将发生更改,例如版本更改

  • 您可以使用Sinon。@robertklep我注意到,我就是无法让它工作。如果您共享不工作的代码,人们会更容易帮助您。@robertklep我最好承认,我不知道从哪里开始使用Sinon存根和测试fs。恐怕还没有测试代码。这里有一些东西让您开始:它存根
    fs.existsSync
    总是返回false,存根还用于检查是否使用正确的文件名调用它。对,但我想存根的fs-这是正确的方式来测试的情况下,文件系统无法访问或通过一个缓慢的远程连接。