【发布时间】:2017-10-08 06:04:27
【问题描述】:
我想使用 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 依赖于 rewire,但我想避免额外的依赖,并且 rewire 也与 babel 不兼容。
【问题讨论】:
-
您可以使用诗乃
stubs。 -
@robertklep 我已经注意到了,我就是无法让它工作。
-
如果您共享不起作用的代码,人们会更容易帮助您。
-
@robertklep 我最好承认,当涉及到 sinon 存根和测试 fs 时,我不知道从哪里开始。恐怕还没有测试代码。
-
这里有一些东西可以帮助您入门:gist.github.com/robertklep/6f6b9aacf80f16334883c647d41c9d12 它存根
fs.existsSync始终返回 false,并且存根还用于检查是否使用正确的文件名调用它。