node.js 无法在集成测试中上传文件

node.js can't upload file in integration test

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

测试:

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()
}

我对节点没有经验,我一定是错过了一些配置什么的。我怎样才能让我的测试通过(不修改外部模块的代码)?

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

此代码中的

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

(来自 busboy 文档):

you should always handle the stream no matter if you care about the file contents or not (e.g. you can simply just do stream.resume(); if you want to discard the contents)

但 Multer 不应该那样做!

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

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

并且如你所见,回调的第二个参数是true,也就是includeFile.

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

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