我正在尝试为方法编写单元测试用例uploadFiles()
。这个方法返回函数,所以我必须检查toHaveBeenCalledWith('files', 5)
。我在下面更新了我的测试用例,我不知道如何模拟返回函数upload.array
。谁能告诉我这可能吗?
方法
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
};
测试用例
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);
});
});
});