Mocking a File object in NestJs unit test with Jest

Viewed 232

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

0 Answers
Related