英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论