Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tests in the upload module (Controllers and Services) #91

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 20 additions & 20 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,27 +80,27 @@
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"coverageThreshold": {
"global": {
"branches": 85,
"functions": 85,
"lines": 85,
"statements": 85
}
},
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": ["**/*.(t|j)s"],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"coverageThreshold": {
"global": {
"branches": 85,
"functions": 85,
"lines": 85,
"statements": 85
}
},
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": ["**/*.(t|j)s"],
"coverageDirectory": "../coverage",
"testEnvironment": "node",
"moduleNameMapper": {
"^src/(.*)$": "<rootDir>/$1"
}
},
"pre-push": [
"test:cov"
],
Expand Down
47 changes: 47 additions & 0 deletions src/modules/upload/__tests__/controllers/post-file.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UploadController } from '../../upload.controller';
import { FileUploadService } from '../../upload.service';
import { AuthGuard } from '@nestjs/passport';

describe('UploadController', () => {
let uploadController: UploadController;
let fileUploadService: FileUploadService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UploadController],
providers: [
{
provide: FileUploadService,
useValue: {
upload: jest.fn(),
},
},
],
})
.overrideGuard(AuthGuard('default'))
.useValue({ canActivate: jest.fn(() => true) })
.compile();

uploadController = module.get<UploadController>(UploadController);
fileUploadService = module.get<FileUploadService>(FileUploadService);
});

it('should return the file location on successful upload', async () => {
const mockFile = { buffer: Buffer.from('test file content') };
const mockResponse = {
Location: 'https://s3.amazonaws.com/bucket/file.txt',
ETag: '12345abcde',
key: 'file.txt',
VersionId: '123456789',
Bucket: 'my-bucket',
};

jest.spyOn(fileUploadService, 'upload').mockResolvedValue(mockResponse);

const result = await uploadController.upload(mockFile);

expect(fileUploadService.upload).toHaveBeenCalledWith(mockFile);
expect(result).toBe(mockResponse.Location);
});
});
44 changes: 44 additions & 0 deletions src/modules/upload/__tests__/services/delete-file.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { InternalServerErrorException } from '@nestjs/common';
import { FileUploadService } from '../../upload.service';

jest.mock('aws-sdk', () => {
return {
S3: jest.fn().mockImplementation(() => ({
deleteObject: jest.fn(),
})),
};
});

describe('FileUploadService', () => {
let fileUploadService: FileUploadService;
let mockDeleteObject: jest.Mock;

beforeEach(() => {
fileUploadService = new FileUploadService();
mockDeleteObject = (fileUploadService as any).s3.deleteObject;
});

it('should call deleteObject and not throw an error on success', async () => {
mockDeleteObject.mockReturnValueOnce({
promise: jest.fn().mockResolvedValue({}),
});

await fileUploadService.deleteFile('some-file-name');

expect(mockDeleteObject).toHaveBeenCalledWith({
Bucket: process.env.AWS_S3_BUCKET_NAME,
Key: 'some-file-name',
});
expect(mockDeleteObject).toHaveBeenCalledTimes(1);
});

it('should throw an InternalServerErrorException on error', async () => {
mockDeleteObject.mockReturnValueOnce({
promise: jest.fn().mockRejectedValue(new Error('Some error')),
});

await expect(fileUploadService.deleteFile('some-file-name')).rejects.toThrowError(
InternalServerErrorException,
);
});
});
37 changes: 37 additions & 0 deletions src/modules/upload/__tests__/services/upload.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { FileUploadService } from '../../upload.service';

describe('FileUploadService', () => {
let uploadService: FileUploadService;

beforeEach(() => {
uploadService = new FileUploadService();
});

it('Should upload the file to AWS S3 and return its data', async () => {
const file = {
buffer: 'buffer',
originalname: 'example-image.jpg',
};

const mockS3Response = {
ETag: '"some-etag-value"',
Location: 'https://bucket-name.s3.amazonaws.com/test-image.jpg',
key: 'test-image.jpg',
Bucket: 'bucket-name',
VersionId: 'version-id',
};

jest.spyOn(uploadService, 'uploadS3').mockResolvedValue(mockS3Response);

const result = await uploadService.upload(file, 'image/jpeg');

expect(uploadService.uploadS3).toHaveBeenCalledWith(
file.buffer,
process.env.AWS_S3_BUCKET_NAME,
file.originalname,
'image/jpeg',
);

expect(result).toEqual(mockS3Response);
});
});
65 changes: 65 additions & 0 deletions src/modules/upload/__tests__/services/uploadS3-file.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { FileUploadService } from '../../upload.service';
import { Logger } from "@nestjs/common";

// Mock da implementação do S3
jest.mock('aws-sdk', () => {
return {
S3: jest.fn(() => ({
upload: jest.fn((params, callback) => {
callback(null, { Location: 'https://s3.amazonaws.com/bucket/file.txt' });
}),
})),
};
});

describe('FileUploadService', () => {
let fileUploadService;

beforeEach(() => {
fileUploadService = new FileUploadService();
fileUploadService.s3 = new (require('aws-sdk').S3)();
});

it('should upload file to S3 successfully', async () => {
const file = Buffer.from('test file content');
const bucket = 'my-test-bucket';
const name = 12345;

const result = await fileUploadService.uploadS3(
file,
bucket,
name,
'text/plain',
);

expect(fileUploadService.s3.upload).toHaveBeenCalledWith(
{
Bucket: bucket,
Key: expect.any(String),
Body: file,
ContentType: 'text/plain',
},
expect.any(Function),
);

expect(result).toEqual({
Location: 'https://s3.amazonaws.com/bucket/file.txt',
});
});

it('should handle upload error', async () => {
fileUploadService.s3.upload.mockImplementationOnce((params, callback) => {
callback({ message: 'Upload failed' }, null);
});

const file = Buffer.from('test file content');
const bucket = 'my-test-bucket';
const name = 12345;

jest.spyOn(Logger, 'error').mockImplementation(() => {});

await expect(fileUploadService.uploadS3(file, bucket, name, 'text/plain')).rejects.toEqual('Upload failed');

expect(fileUploadService.s3.upload).toHaveBeenCalled();
});
});
6 changes: 0 additions & 6 deletions src/modules/upload/__tests__/upload.controller.spec.ts

This file was deleted.

6 changes: 0 additions & 6 deletions src/modules/upload/__tests__/upload.service.spec.ts

This file was deleted.