Javascript Node.js单元测试:fs模块抛出错误时的测试行为?
当Javascript Node.js单元测试:fs模块抛出错误时的测试行为?,javascript,node.js,unit-testing,Javascript,Node.js,Unit Testing,当fs模块函数抛出错误时,如何测试模块的行为?我有以下代码: fs.stat('/Users/' + username.sync() + '/Library/LaunchAgents/' + key + '.plist', function(error, stat) { if (!error) { callback(null, true); } else if (error.code == 'ENOENT') { callback(null, false); } else {
fs
模块函数抛出错误时,如何测试模块的行为?我有以下代码:
fs.stat('/Users/' + username.sync() + '/Library/LaunchAgents/' + key + '.plist', function(error, stat) {
if (!error) {
callback(null, true);
} else if (error.code == 'ENOENT') {
callback(null, false);
} else {
callback(error, null);
}
return;
});
但目前,在测试过程中,else
路径从未运行过。覆盖这条线的最佳实践方式是什么
谢谢这里有一个常见系统错误列表:您可以使用描述触发一些错误。你不能测试所有的文件,但是有一些很简单的,例如,更改文件的权限,你会有一个EACCES错误。如果你不想摆弄实际的文件,你可以使用像
sinon
这样的模块来存根fs
。这样,您就可以使用您选择的错误调用fs.stat
回调