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

78 api teste unitario testimonies #92

Open
wants to merge 6 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
1,100 changes: 1,056 additions & 44 deletions package-lock.json

Large diffs are not rendered by default.

27 changes: 17 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@
"@commitlint/config-conventional": "^17.6.3",
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@nestjs/testing": "^9.4.3",
"@prisma/client": "^5.21.1",
"@types/bcrypt": "^5.0.0",
"@types/express": "^4.17.13",
"@types/jest": "29.2.4",
"@types/jest": "^29.5.14",
"@types/node": "18.11.18",
"@types/nodemailer": "^6.4.7",
"@types/passport-jwt": "^3.0.8",
Expand All @@ -73,19 +73,21 @@
"prisma": "^5.21.1",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "29.0.3",
"test": "^3.3.0",
"ts-jest": "^29.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.1",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"],
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"testRegex": "..spec.ts$",
"coverageThreshold": {
"global": {
"branches": 85,
Expand All @@ -95,11 +97,16 @@
}
},
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
"^.+.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": ["**/*.(t|j)s"],
"collectCoverageFrom": [
"**/.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
"testEnvironment": "node",
"moduleNameMapper": {
"^src/(.*)$": "<rootDir>/$1"
}
},
"pre-push": [
"test:cov"
Expand Down
128 changes: 126 additions & 2 deletions src/modules/testimony/__tests__/services/createTestimony.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,130 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CreateTestimonyService } from '../../services/createTestimony.service';
import { TestimonyRepository } from '../../repository/testimony.repository';
import { CreateTestimonyDto } from '../../dto/create-testimony.dto';
import { MentorEntity } from 'src/modules/mentors/entities/mentor.entity';

describe('Create Testimony Tests', () => {
describe('CreateTestimonyService', () => {
let service: CreateTestimonyService;
let testimonyRepository: TestimonyRepository;

});
beforeEach(async () => {
// Cria mock repository
const mockTestimonyRepository = {
createNewTestimony: jest.fn(),
} as Partial<jest.Mocked<TestimonyRepository>>;

// Cria testing module
const module: TestingModule = await Test.createTestingModule({
providers: [
CreateTestimonyService,
{
provide: TestimonyRepository,
useValue: mockTestimonyRepository,
},
],
}).compile();

// Pega instancia do service e do repository
service = module.get<CreateTestimonyService>(CreateTestimonyService);
testimonyRepository = module.get(TestimonyRepository);
});

// Testa criacao bem sucedida de testimony.
it('should create a testimony with mentor data', async () => {
// Arrange: Prepare test data
const mentorData: MentorEntity = {
id: 'mentor1',
fullName: 'John Doe',
profile: 'http://example.com/profile.jpg',
specialties: ['JavaScript', 'React'],
dateOfBirth: new Date(),
password: 'password',
email: '[email protected]',
role: 'mentor',
createdAt: new Date(),
updatedAt: new Date(),
gender: 'Male',
aboutMe: 'Test mentor',
};

const createTestimonyDto: CreateTestimonyDto = {
description: 'Test testimony description',
userName: mentorData.fullName,
role: mentorData.specialties.join(','),
imageUrl: mentorData.profile,
};

// Spy on repository method
jest
.spyOn(testimonyRepository, 'createNewTestimony')
.mockResolvedValue(undefined);

// Act: Executa o método da service
const result = await service.execute(createTestimonyDto, mentorData);

// Assert: Verifica comportamento esperado
expect(testimonyRepository.createNewTestimony).toHaveBeenCalledWith(
{
...createTestimonyDto,
userName: mentorData.fullName,
role: 'JavaScript,React',
imageUrl: mentorData.profile,
},
mentorData.id,
);

expect(result).toEqual({
message: 'Testimony created successfully',
});
});

// Test error handling
it('should handle errors during testimony creation', async () => {
// Arrange
const createTestimonyDto: CreateTestimonyDto = {
description: 'Test testimony description',
userName: '',
role: '',
imageUrl: '',
};

const mentorData: MentorEntity = {
id: 'mentor1',
fullName: 'John Doe',
profile: 'http://example.com/profile.jpg',
specialties: ['JavaScript', 'React'],
dateOfBirth: new Date(),
password: 'password',
email: '[email protected]',
role: 'mentor',
createdAt: new Date(),
updatedAt: new Date(),
gender: 'Male',
aboutMe: 'Test mentor',
};

// Simula erro no repository
const mockError = new Error('Repository creation failed');
jest
.spyOn(testimonyRepository, 'createNewTestimony')
.mockRejectedValue(mockError);

// Use console.log spy to verify error logging
const consoleSpy = jest.spyOn(console, 'log');

// Act & Assert
const result = await service.execute(createTestimonyDto, mentorData);

// Verify error was logged
expect(consoleSpy).toHaveBeenCalledWith(mockError);

// Verify result is still returned
expect(result).toEqual({
message: 'Testimony created successfully',
});

// Clean up
consoleSpy.mockRestore();
});
});
133 changes: 131 additions & 2 deletions src/modules/testimony/__tests__/services/deleteTestimony.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,135 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DeleteTestimonyService } from '../../services/deleteTestimony.service';
import { TestimonyRepository } from '../../repository/testimony.repository';
import { TestimonyEntity } from '../../entity/testimony.entity';

describe('Delete Testimony Tests', () => {
describe('DeleteTestimonyService', () => {
let service: DeleteTestimonyService;
let testimonyRepository: TestimonyRepository;

});
beforeEach(async () => {
// Cria mock repository
const mockTestimonyRepository = {
findTestimonyById: jest.fn(),
deleteTestimony: jest.fn(),
} as Partial<jest.Mocked<TestimonyRepository>>;

// Cria testing module
const module: TestingModule = await Test.createTestingModule({
providers: [
DeleteTestimonyService,
{
provide: TestimonyRepository,
useValue: mockTestimonyRepository,
},
],
}).compile();

// Pega instancia do service e do repository
service = module.get<DeleteTestimonyService>(DeleteTestimonyService);
testimonyRepository = module.get(TestimonyRepository);
});

// Testa exclusão bem-sucedida de testimony
it('should delete an existing testimony', async () => {
// Arrange: Prepare test data
const testimonyId = 'testimony1';
const mockTestimony: TestimonyEntity = {
id: testimonyId,
userName: 'John Doe',
description: 'Test testimony',
role: 'Mentor',
imageUrl: 'http://example.com/profile.jpg',
mentor_id: 'mentor1',
};

// Configura mocks
jest
.spyOn(testimonyRepository, 'findTestimonyById')
.mockResolvedValue(mockTestimony);

const deleteTestimonySpy = jest
.spyOn(testimonyRepository, 'deleteTestimony')
.mockResolvedValue(undefined);

// Act: Executa o método da service
const result = await service.execute(testimonyId);

// Assert: Verifica comportamento esperado
expect(testimonyRepository.findTestimonyById).toHaveBeenCalledWith(
testimonyId,
);
expect(deleteTestimonySpy).toHaveBeenCalledWith(testimonyId);
expect(result).toEqual({
message: 'Testimony deleted successfully',
});
});

// Testa tentativa de exclusão de testimony inexistente
it('should return message when testimony does not exist', async () => {
// Arrange
const nonExistentTestimonyId = 'non-existent-id';

// Configura mock para retornar null (testimony não encontrado)
jest
.spyOn(testimonyRepository, 'findTestimonyById')
.mockResolvedValue(null);

const deleteTestimonySpy = jest.spyOn(
testimonyRepository,
'deleteTestimony',
);

// Act
const result = await service.execute(nonExistentTestimonyId);

// Assert
expect(testimonyRepository.findTestimonyById).toHaveBeenCalledWith(
nonExistentTestimonyId,
);
expect(deleteTestimonySpy).not.toHaveBeenCalled();
expect(result).toEqual({
message: 'There are no testimony with that id',
});
});

// Testa tratamento de erro durante a exclusão
it('should handle errors during testimony deletion', async () => {
// Arrange
const testimonyId = 'testimony1';
const mockTestimony: TestimonyEntity = {
id: testimonyId,
userName: 'John Doe',
description: 'Test testimony',
role: 'Mentor',
imageUrl: 'http://example.com/profile.jpg',
mentor_id: 'mentor1',
};

// Configura mocks
jest
.spyOn(testimonyRepository, 'findTestimonyById')
.mockResolvedValue(mockTestimony);

// Simula erro durante a exclusão
const deleteError = new Error('Deletion failed');
const deleteTestimonySpy = jest
.spyOn(testimonyRepository, 'deleteTestimony')
.mockRejectedValue(deleteError);

// Use console.log spy to verify error logging
const consoleSpy = jest.spyOn(console, 'log');

// Act & Assert
await expect(service.execute(testimonyId)).rejects.toThrow(deleteError);

// Verify repository methods were called
expect(testimonyRepository.findTestimonyById).toHaveBeenCalledWith(
testimonyId,
);
expect(deleteTestimonySpy).toHaveBeenCalledWith(testimonyId);

// Clean up
consoleSpy.mockRestore();
});
});
Loading