Testing binary response with supertest

huangapple go评论78阅读模式
英文:

Testing binary response with supertest

问题

我正在使用Express开发API,并使用supertest进行测试。我的API端点返回tar.gz文件。我想测试文件是否正确发送并且内容正确。我在弄清楚如何检索数据方面遇到了困难。我最初的尝试是将res.text的内容(其中const res = request(app).get('/project/export'))保存到文件中,然后解压它并检查其内容。但是简单保存res.text似乎不起作用,而提取函数也不认为它是正确压缩的文件。

任何帮助都会受到欢迎。请随时建议其他模块/方法来测试Express应用程序。谢谢!

英文:

I'm developing an API with express and testing it with supertest. My API endpoint is returning tar.gz file. I would like to test, if file is properly sent and it's content is correct. I'm having troubles figuring out how to retrieve data. My naive approach was to save content of res.text (where const res = request(app).get('/project/export') to a file, extract it and check it's content. But simple saving of res.text does not seem to work and extracting function does not recognise it as properly compressed file.

Any help appreciated. Feel free to suggest other modules/approaches how to test an express app. Thanks!

答案1

得分: 6

在Jest中运行测试时,在请求上设置.responseType('blob')将导致response.body是一个Buffer

https://visionmedia.github.io/superagent/#binary

例如:

const response = await request(app)
  .get('/project/export')
  .responseType('blob')

await fs.promises.writeFile('export.tar.gz', response.body)
英文:

When running tests in Jest, setting .responseType('blob') on the request will cause response.body to be a Buffer.

https://visionmedia.github.io/superagent/#binary

For example:

const response = await request(app)
  .get('/project/export')
  .responseType('blob')

await fs.promises.writeFile('export.tar.gz', response.body)

huangapple
  • 本文由 发表于 2020年1月3日 18:07:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定