是否可以使用 "mock-fs" 进行模拟?库出现某种读取文件错误?特别是,我想测试这种情况(其中 code !== 'ENOENT'
):
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code !== 'ENOENT') {
return done(new ReadingFileError(filePath));
}
}
// ...
});
我在他们的文档中找不到任何有关模拟阅读错误的信息。也许还有其他一些库可以做到这一点。
最佳答案
据我所知,mock-fs 模拟文件系统而不是 Node 实用程序。当然,在某些情况下,您可以使用它来测试 fs 实用程序,但我认为您的用例不在其中。
这是一个带有 sinon.sandbox 的示例
一些替代方案是:
- proxyquire (参见下面的示例)
- testdouble
Note, that I am a bit confused where the
ReadingFileError
comes from, so I guess you are trying to implement a custom error. If that is the case maybe this also will be helpful. In the example I replaced that with a simplenew Error('My !ENOENT error')
.
// readfile.js
'use strict'
const fs = require('fs')
function myReadUtil (filePath, done) {
fs.readFile(filePath, (err, data) => {
if (err) {
if (err.code !== 'ENOENT') {
return done(err, null)
}
return done(new Error('My ENOENT error'), null)
}
return done(null, data)
})
}
module.exports = myReadUtil
// test.js
'use strict'
const assert = require('assert')
const proxyquire = require('proxyquire')
const fsMock = {
readFile: function (path, cb) {
cb(new Error('My !ENOENT error'), null)
}
}
const myReadUtil = proxyquire('./readfile', { 'fs': fsMock })
myReadUtil('/file-throws', (err, file) => {
assert.equal(err.message, 'My !ENOENT error')
assert.equal(file, null)
})
编辑:重构示例以使用 Node 样式回调,而不是 throw
和 try/catch
关于node.js - 模拟 Node.js 中测试的特定读取文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53333758/