代码之家  ›  专栏  ›  技术社区  ›  Serg

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

  •  1
  • Serg  · 技术社区  · 6 年前

    有没有可能用 "mock-fs" 库中是否存在某种读取文件错误?特别是,我想测试这个案例(在 code !== 'ENOENT' ):

    fs.readFile(filePath, (err, data) => {
        if (err) {
            if (err.code !== 'ENOENT') { 
                return done(new ReadingFileError(filePath));
            }
        }
        // ... 
    });
    

    我对模仿他们的文档中的阅读错误一无所知。也许还有其他一些图书馆可以做到这一点。

    1 回复  |  直到 6 年前
        1
  •  1
  •   lependu    6 年前

    据我所知 mock-fs 模拟文件系统,而不是节点实用程序。当然,在某些情况下,您可以使用它来测试fs实用程序,但我认为您的用例并没有处理它们。

    下面是一个例子 sinon.sandbox

    一些替代方案是:

    注意,我有点困惑 ReadingFileError 来自,所以我猜您正在尝试实现一个自定义错误。如果是这样的话,也许 this 也会有帮助。在这个例子中,我用一个简单的 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)
    })
    

    编辑 :将示例重构为使用节点样式回调而不是 throw try/catch