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

Melhoria/testes #4

Merged
merged 4 commits into from
Feb 16, 2025
Merged
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
44 changes: 44 additions & 0 deletions src/usuario/email.senha.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import nodemailer from 'nodemailer';
import { sendResetEmail } from './email.senha'; // Ajuste o caminho conforme necessário

// Mock do módulo nodemailer
jest.mock('nodemailer', () => ({
createTransport: jest.fn().mockReturnValue({
sendMail: jest.fn().mockResolvedValue({ messageId: '12345' }),
}),
}));

describe('sendResetEmail', () => {
const email = '[email protected]';
const codigo = '123456';

it('deve enviar o e-mail de redefinição de senha', async () => {
await sendResetEmail(email, codigo);

// Verifica se o transporte de e-mail foi criado com o Gmail
expect(nodemailer.createTransport).toHaveBeenCalledWith({
service: 'Gmail',
auth: {
user: '[email protected]', // Insira seu e-mail real ou o da aplicação
pass: 'wktc yjut lzvc anda', // Senha do aplicativo
},
});

// Verifica se a função sendMail foi chamada com os parâmetros esperados
expect(nodemailer.createTransport().sendMail).toHaveBeenCalledWith({
from: '"Sistema" <[email protected]>',
to: email,
subject: 'Redefinição de Senha',
text: `Seu código de redefinição é: ${codigo}`,
});

// Verifica se o envio foi bem-sucedido
const response = await nodemailer.createTransport().sendMail({
from: '"Sistema" <[email protected]>',
to: email,
subject: 'Redefinição de Senha',
text: `Seu código de redefinição é: ${codigo}`,
});
expect(response.messageId).toBe('12345');
});
});
52 changes: 51 additions & 1 deletion src/usuario/usuario.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Buffer } from 'buffer';
import { Filtering } from '../shared/decorators/filtrate.decorator';
import { OrderParams, Ordering } from '../shared/decorators/ordenate.decorator';
import {
Pagination,
PaginationParams,
} from '../shared/decorators/paginate.decorator';
import { EsqueciSenhaDto } from './dto/esqueci-senha.dto';
import { ResetarSenhaDto } from './dto/resetar-senha.dto';
import { Usuario } from './entities/usuario.entity';
import { IUsuarioFilter } from './interfaces/usuario-filter.interface';
import { UsuarioController } from './usuario.controller';
Expand All @@ -22,7 +25,9 @@ describe('UsuarioController', () => {
foto: '1',
admin: false,
created_at: new Date(), // adicione isso
updated_at: new Date()
updated_at: new Date(),
descricao: 'Descrição do usuário',
data_nascimento: new Date()
};

const user = {
Expand All @@ -45,6 +50,8 @@ describe('UsuarioController', () => {
update: jest.fn(),
findAll: jest.fn(),
findAllToPublicacao: jest.fn(),
enviarCodigoRedefinicao: jest.fn(),
resetarSenha: jest.fn(),
},
},
{
Expand Down Expand Up @@ -93,6 +100,49 @@ describe('UsuarioController', () => {
expect(response.message).toEqual('Atualizado com sucesso!');
});

it('should handle esqueciSenha request', async () => {
jest.spyOn(service, 'enviarCodigoRedefinicao').mockResolvedValue({ message: 'Código enviado' });

const dto: EsqueciSenhaDto = { email: '[email protected]' };
const response = await controller.esqueciSenha(dto);

expect(service.enviarCodigoRedefinicao).toHaveBeenCalledWith(dto.email);
expect(response.message).toBe('Código enviado');
});

it('should throw BadRequestException if email is missing in esqueciSenha', async () => {
const dto: EsqueciSenhaDto = { email: '' }; // email vazio para forçar a exceção
try {
await controller.esqueciSenha(dto);
} catch (e: unknown) {
const error = e as any;
expect(error.response.statusCode).toBe(400); // Exceção esperada (BadRequest)
expect(error.response.message).toBe('O campo "email" é obrigatório');
}
});

it('should handle resetarSenha request', async () => {
const resetDto: ResetarSenhaDto = { email: '[email protected]', codigo: '123456', novaSenha: 'novaSenha123' };

jest.spyOn(service, 'resetarSenha').mockResolvedValue({ message: 'Senha redefinida' });

const response = await controller.resetarSenha(resetDto);

expect(service.resetarSenha).toHaveBeenCalledWith(resetDto);
expect(response.message).toBe('Senha redefinida');
});

it('should throw BadRequestException if email is missing in resetarSenha', async () => {
const dto: ResetarSenhaDto = { email: '', codigo: '123456', novaSenha: 'novaSenha123' };
try {
await controller.esqueciSenha(dto);
} catch (e: unknown) {
const error = e as any;
expect(error.response.statusCode).toBe(400);
expect(error.response.message).toBe('O campo "email" é obrigatório');
}
});

describe('findAll', () => {
const filter: IUsuarioFilter = {
nome: 'Henrique',
Expand Down
Loading