用嘲笑在Nestjs单元测试中模拟文件对象
我最近开始使用nest.js及其内置单元测试库开玩笑,而在上传一个.csv文件并在其上执行某些操作的任务,我决定也单位测试端点,这要求我模拟该端点CSV文件对象,因此
const mockFile = {
fieldname: 'file',
originalname: 'TradeHistory.csv',
encoding: '7bit',
mimetype: 'text/csv',
buffer: Buffer.from(__dirname + '/../../TradeHistory.csv', 'utf8'),
size: 51828,
}
我很快就遇到了这些问题;
- 对于文件上传,我使用的是@useInterceptors()和@uploadedfile()
- ,它采用 file的类型:express.multer.file.file
- ,它不接受我的模拟文件 object 类型作为参数,
因此我搜索了一种将模拟文件转换为类型 express.multer.file 的方法 一段时间后,对我有用的事情变得令人尴尬而直接,就像使用类型的断言作为关键字铸造文件对象 express.multer.file.file
const mockFile = {
fieldname: 'file',
originalname: 'TradeHistory.csv',
encoding: '7bit',
mimetype: 'text/csv',
buffer: Buffer.from(__dirname + '/../../TradeHistory.csv', 'utf8'),
size: 51828,
} as Express.Multer.File
其他方式可能存在,我愿意接受建议
I recently started working with Nest.js and its built-in unit testing library Jest, while on a task to upload a .CSV file and perform some operations on it, I decided to also unit test the endpoint and this required me to mock the CSV file object, which I did as thus
const mockFile = {
fieldname: 'file',
originalname: 'TradeHistory.csv',
encoding: '7bit',
mimetype: 'text/csv',
buffer: Buffer.from(__dirname + '/../../TradeHistory.csv', 'utf8'),
size: 51828,
}
I quickly ran into these issues;
- For file upload, I was using the @UseInterceptors() and @UploadedFile()
- which takes a type of file: Express.Multer.File
- Which won't accept my mocked file object type as an argument
So I searched for a way to convert the mocked file into a type Express.Multer.File
and after a while what worked for me turned out to be embarrassingly simple and straightforward as using the type assertion as keyword to cast the file object Express.Multer.File
const mockFile = {
fieldname: 'file',
originalname: 'TradeHistory.csv',
encoding: '7bit',
mimetype: 'text/csv',
buffer: Buffer.from(__dirname + '/../../TradeHistory.csv', 'utf8'),
size: 51828,
} as Express.Multer.File
Other ways might exist, I'm open to suggestions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论