i am trying to write unit test case for uploadFiles()
method. This method returns function so i have to check toHaveBeenCalledWith('files', 5)
. I have updated my test case below, I don't know how to mock return function upload.array
. can anyone tell me is that possible?
Method
uploadFiles = (
storage: StorageType,
validationFn: (request: Request, file: Express.Multer.File, cb: FileFilterCallback) => Promise<void>,
) => {
// fileSize - size of an individual file (1024 * 1024 * 1 = 1mb)
const upload = multer({
storage: this[storage](),
limits: { fileSize: 1024 * 1024 * FILE_SIZE },
fileFilter: this.fileUtil.fileValidation(validationFn),
});
return upload.array("files", 5); // maximum files allowed to upload in a single request
};
Test Case
describe('FileService', () => {
// fileValidation Test suite
describe('fileValidation', () => {
let callbackFn: jest.Mock<any, any>;
let validationFn: jest.Mock<any, any>;
beforeEach(() => {
callbackFn = jest.fn();
validationFn = jest.fn();
});
afterEach(() => {
callbackFn.mockClear();
validationFn.mockClear();
});
it('should call the file filter method with image file types when request body has type image', async () => {
// Preparing
const request = {
body: {
entity_no: 'AEZ001',
type: 'image',
category: 'Shipping',
},
};
const file = {
originalname: 'some-name.png',
mimetype: 'image/png',
};
// Executing
const func = fileService.uploadFiles(StorageType.DISK, validationFn);
await func(request as Request, file as any, callbackFn);
});
});
});
You can use jest.mock(moduleName, factory, options) to mock
multer
module.E.g.
fileService.ts
:fileService.test.ts
:unit test result: