【问题标题】:node.js can't upload file in integration testnode.js 无法在集成测试中上传文件
【发布时间】:2017-09-28 03:19:50
【问题描述】:

我在重构之前将集成测试添加到旧代码库。对于这种情况,上传文件。

测试:

it('uploads a photo at the specified index', done => {

    chai.request(server.instance)
        .post('/profile/photo/0')
        .set('Access-Token', `${token}`)
        .set('API-Key', testConfig.apiKey)
        .field({contentId: 'foobar'})
        .attach('file', fs.readFileSync(__dirname + '/logo.png'), 'file')
        .end((err, res) => {
            console.log(JSON.stringify(res.body))
            res.should.have.status(200)


            done()
        })
}) 

正在测试的端点在生产中工作正常。但是要让测试通过,我必须在multer 模块的make-middleware.js 中注释掉以下行:

if (!includeFile) {
  // appender.removePlaceholder(placeholder)
  // return fileStream.resume()
}

由于对节点没有经验,我一定错过了一些配置或其他东西。我怎样才能使我的测试通过(不修改外部模块的代码)?

【问题讨论】:

  • 您是否 100% 确信 fs.readFileSync(__dirname + '/logo.png') 会读取文件?顺便说一句:使用path.join( __dirname, 'logo.png' ) 是个好主意,这样它就不会在 Windows 上失败。
  • @pawel 是的,绝对相信它被正确读取。关于 windows 的好提示,谢谢。
  • 您是否使用过端点(在此测试之外)发布了相同的文件 (logo.png)。好像您已经在服务器上为 multer 定义了一个文件过滤器,但该文件没有通过它...

标签: javascript node.js multer


【解决方案1】:

multer 使用busboy 完成其工作(获取/流式传输文件)。您评论的行只是停止流:

此代码中的fileStream.resume() 等效于busboy 代码中的stream.resume(),因此它只是丢弃流:

(来自busboy 文档):

无论您是否关心 文件内容与否(例如,你可以简单地做stream.resume(); if 你想丢弃内容)

但 Multer 不应该那样做!

只有当你向 Multer 传递一个自定义 fileFilter 并带有一个将 includeFile 设置为 false 的回调时,它才会这样做。
否则,如果您没有 fileFilter 选项,Multer 将使用以下默认 fileFilter(什么都不做):

function allowAll (req, file, cb) {
  cb(null, true)
}

而且可以看到,回调的第二个参数是true,也就是includeFile

因此,您可以检查您的自定义 fileFilter(如果有的话),如果没有,这可能是一个意想不到的副作用,我祝您好运!

希望对你有帮助,
最好的问候

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 2021-05-09
相关资源
最近更新 更多