0

我正在尝试涵盖单元测试用例removeFiles方法。对于 AWS S3,我尝试模拟s3.deleteObjects一个开关案例有人能建议我怎么做吗?

方法

import S3 from 'aws-sdk/clients/s3';
container.register(S3, { useValue: new S3(AWS_OPTIONS) });

 removeFiles = async (files: FileDocumentType[], cb: FileFilterCallback) => {
    const removedIds = [];
    const deleteS3Objects = [];
    for (const file of files) {
      const { _id, file_name, file_category} = file;
      deleteS3Objects.push({
        Key: `${file_category}/${file_name}`,
      });
      removedIds.push(_id);
    }
    if (!isEmpty(deleteS3Objects)) {
      const response = await this.s3
        .deleteObjects({
          Bucket: c.getEnv('AWS_BUCKET'),
          Delete: { Objects: deleteS3Objects },
        })
        .promise();
      if (isEmpty(response.Deleted)) {
        return cb(e.fileRemoveError);
      }
    }
    return removedIds;
  };

测试用例

jest.mock('aws-sdk', () => {
  const deleteObjectOutputMock = {
    promise: jest.fn(),
  };
  const deleteObjectMock = jest.fn(() => deleteObjectOutputMock);

  const mS3 = {
    deleteObject: deleteObjectMock,
  };
  return { S3: jest.fn(() => mS3) };
});
 describe('removeFiles', () => {
     it('should delete image from AWS and return deleted document ID ', async () => {
      // Preparing
      const files = [
        {
          _id: oId('5fd99ea26a3c872e6f09dc0b'),
          file_status_is_active: true,
          file_name: 'pmt000057-6876316629400-2.png',
          file_entity_no: 'PMT000057',
          file_type: FileType.Image,
          file_category: EntityType.Promotion,
          file_storage: StorageType.AWS_S3,
          file_path: 'uploads/pmt000057-6876316629400-2.png',
          file_no: 'FLE000005',
          __v: 0,
          file_created_date: new Date('2020-12-16T05:44:02.920Z'),
          file_modified_date: new Date('2020-12-16T05:44:02.920Z'),
        },
      ];
      const respones = {
        Deleted: [{ Key: 'Promotion/pmt000057-6876316629400-2.png' }],
        Errors: [],
      };
      const df = new S3();
      jest.spyOn(df, 'deleteObjects').mockReturnValueOnce(respones as any);
      // Executing
       await fileService.removeFiles(files, callbackFn);
      expect(result).toEqual([oId('5fd99ea26a3c872e6f09dc0b')]);
    });
  });
```
4

0 回答 0