Home > Mobile >  How can I mock a file upload in nestjs?
How can I mock a file upload in nestjs?

Time:08-26

I have a method in my controller that accepts a csv file sent as form-data.

import csv = require('csvtojson');

@Post('/create')
@UseInterceptors(FileInterceptor('file'))
async createUsers(@Query() query: RequestDTO, @UploadedFile() file: Express.Multer.File) {
 const createJson = await csv().fromString(file.buffer.toString('utf-8'));
 const response = this.myService.createUsers(query, createJson);
 return response;
}

I just want to be able to mock it using Jest but I am not sure how to go about it.

CodePudding user response:

You can simply forge file parameter with the correct properties.

const file: Express.Multer.File = {
  originalname: 'file.csv',
  mimetype: 'text/csv',
  path: 'something',
  buffer: Buffer.from('one,two,three'),
};        

In your test file when you call your createUser you can pass it as a second parameter

This could be helpful

  • Related