node.js - 模拟 Node.js 中测试的特定读取文件错误

标签 node.js unit-testing mocking fs

是否可以使用 "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 的示例

一些替代方案是:

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 simple new 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 样式回调,而不是 throwtry/catch

关于node.js - 模拟 Node.js 中测试的特定读取文件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53333758/

相关文章:

python - 数独求解器中未定义全局名称 checkRows

unit-testing - 哪个 C# 模拟框架充分利用了 .NET 4?

c# - 更改字段值的 MOQ Mock void 方法

c# - 我如何使用 Rhino Mocks 检查传递给方法的值

javascript - AngularJS $http.get 无法与 Node.js RESTful 一起使用

node.js - MongoDB:哪个更快:findOne + 如果不存在插入或更新插入?

node.js - 为什么要把http模块和express模块​​结合起来

objective-c - Objc 等效于 STFail 但停止了测试

sql - RSpec:如何现在模拟 SQL()

macos - Mac npm 出现 ENOENT 错误