用嘲笑在Nestjs单元测试中模拟文件对象

发布于 2025-02-12 04:20:03 字数 987 浏览 0 评论 0原文

我最近开始使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文