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