如何模拟从 fs.readFile 返回的错误以进行测试?
How to simulate error returned from fs.readFile for testing purposes?
我是测试驱动开发的新手,正在尝试为我的应用程序开发一个自动化测试套件。
我已经成功编写了测试来验证从成功调用 Node 的 fs.readFile 方法接收到的数据,但是正如您将在下面的屏幕截图中看到的,当我使用 istanbul 模块测试我的覆盖时,它会正确显示我还没有测试从 fs.readFile.
返回错误的情况
我该怎么做?我有一种预感,我必须模拟一个文件系统,我已经尝试使用 mock-fs 模块,但没有成功。该文件的路径在函数中是硬编码的,我正在使用 rewire 从我的应用程序代码中调用未导出的函数。因此,当我使用 rewire 的 getter 方法访问 getAppStatus 函数时,它使用真正的 fs 模块,因为它是 getAppStatus 所在的 async.js 文件中使用的模块。
这是我正在测试的代码:
// check whether the application is turned on
function getAppStatus(cb){
fs.readFile(directory + '../config/status.js','utf8', function(err, data){
if(err){
cb(err);
}
else{
status = data;
cb(null, status);
}
});
}
这是我为返回数据的情况编写的测试:
it('application should either be on or off', function(done) {
getAppStatus(function(err, data){
data.should.eq('on' || 'off')
done();
})
});
我使用 Chai 作为断言库,运行 使用 Mocha 进行测试。
任何允许我模拟从 fs.readFile 返回的错误以便我可以为此场景编写测试用例的任何帮助都非常感谢。
最好使用mock-fs
,如果你不提供文件,它会return ENOENT。
请注意在测试后调用 restore 以避免对其他测试产生任何影响。
加在开头
var mock = require('mock-fs');
和测试
before(function() {
mock();
});
it('should throw an error', function(done) {
getAppStatus(function(err, data){
err.should.be.an.instanceof(Error);
done();
});
});
after(function() {
mock.restore();
});
我是测试驱动开发的新手,正在尝试为我的应用程序开发一个自动化测试套件。
我已经成功编写了测试来验证从成功调用 Node 的 fs.readFile 方法接收到的数据,但是正如您将在下面的屏幕截图中看到的,当我使用 istanbul 模块测试我的覆盖时,它会正确显示我还没有测试从 fs.readFile.
返回错误的情况我该怎么做?我有一种预感,我必须模拟一个文件系统,我已经尝试使用 mock-fs 模块,但没有成功。该文件的路径在函数中是硬编码的,我正在使用 rewire 从我的应用程序代码中调用未导出的函数。因此,当我使用 rewire 的 getter 方法访问 getAppStatus 函数时,它使用真正的 fs 模块,因为它是 getAppStatus 所在的 async.js 文件中使用的模块。
这是我正在测试的代码:
// check whether the application is turned on
function getAppStatus(cb){
fs.readFile(directory + '../config/status.js','utf8', function(err, data){
if(err){
cb(err);
}
else{
status = data;
cb(null, status);
}
});
}
这是我为返回数据的情况编写的测试:
it('application should either be on or off', function(done) {
getAppStatus(function(err, data){
data.should.eq('on' || 'off')
done();
})
});
我使用 Chai 作为断言库,运行 使用 Mocha 进行测试。
任何允许我模拟从 fs.readFile 返回的错误以便我可以为此场景编写测试用例的任何帮助都非常感谢。
最好使用mock-fs
,如果你不提供文件,它会return ENOENT。
请注意在测试后调用 restore 以避免对其他测试产生任何影响。
加在开头
var mock = require('mock-fs');
和测试
before(function() {
mock();
});
it('should throw an error', function(done) {
getAppStatus(function(err, data){
err.should.be.an.instanceof(Error);
done();
});
});
after(function() {
mock.restore();
});