Skip to content

Commit

Permalink
Adiciona testes unitários no login
Browse files Browse the repository at this point in the history
Signed-off-by: DaviMarinho <[email protected]>
  • Loading branch information
DaviMarinho committed Nov 16, 2023
1 parent 34147b1 commit 86a2608
Showing 1 changed file with 52 additions and 26 deletions.
78 changes: 52 additions & 26 deletions src/app/pages/login/login.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ComponentFixture, TestBed, tick, fakeAsync } from '@angular/core/testing';
import { LoginComponent } from './login.component';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { HttpClientTestingModule } from '@angular/common/http/testing';
Expand All @@ -8,40 +8,67 @@ import { ProfileComponent } from '../profile/profile.component';
import { CheckCodeRestPasswordComponent } from '../check-code-rest-password/check-code-rest-password.component';
import { RegisterComponent } from '../register/register.component';
import { of, throwError } from 'rxjs';
import { AlertService } from '../../services/alert.service';
import { MessageService } from 'primeng/api';
import { VideoComponent } from '../video/video.component';

const mockUserReturn = {
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiZW1haWwiOiJqb2FvMTV2aWN0b3IwOEBnbWFpbC5jb20iLCJleHAiOjE2OTkzMTI5MzV9.1B9qBJt8rErwBKyD5JCdsPozsw86oQ38tdfDuMM2HFI",
"token_type": "bearer"
}
};

class AuthServiceMock {
constructor() { }

loginUser() {
return of(mockUserReturn);
return throwError({ error: { message: 'Erro' } });
}
}

class MessageServiceMock {
messages: any[] = [];

add(message: any) {
this.messages.push(message);
}

clear() {
this.messages = [];
}
}

describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let authService: AuthService;
let alertService: AlertService;
let messageService: MessageServiceMock; // Use the mock class

beforeEach(async () => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule.withRoutes(
[
{ path: 'profile', component: ProfileComponent },
{ path: 'sendCodeResetPassword', component: CheckCodeRestPasswordComponent },
{ path: 'register', component: RegisterComponent }
{ path: 'register', component: RegisterComponent },
{ path: 'videos', component: VideoComponent }
]
)],
providers: [FormBuilder, { provide: AuthService, useValue: new AuthServiceMock() }],
providers: [
FormBuilder,
AuthService,
AlertService,
{ provide: MessageService, useClass: MessageServiceMock }, // Provide the mock class
{ provide: AuthService, useClass: AuthServiceMock }
],
declarations: [LoginComponent],
}).compileComponents();

fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
authService = TestBed.inject(AuthService);
alertService = TestBed.inject(AlertService);
messageService = TestBed.inject(MessageService) as unknown as MessageServiceMock; // Inject the mock class
});

it('should create', () => {
Expand All @@ -50,61 +77,60 @@ describe('LoginComponent', () => {

it('should have a valid form on initialization', () => {
fixture.detectChanges();
expect(component.userForm).toBeTruthy();
expect(component.userForm.valid).toBeFalse();
});

it('should call login method when the form is submitted', () => {
it('should call login method when the form is submitted with valid data', fakeAsync(() => {
fixture.detectChanges();
spyOn(component, 'login').and.callThrough();
const form = component.userForm;
form.setValue({ email: '[email protected]', password: 'password' });

const submitButton = fixture.nativeElement.querySelector(
'button[type="submit"]'
);
const submitButton = fixture.nativeElement.querySelector('button[type="submit"]');
submitButton.click();
tick();

expect(component.login).toHaveBeenCalled();
});
}));

it('should call alert when form is not valid', () => {
it('should call alert when form is submitted with invalid data', fakeAsync(() => {
spyOn(component, 'login').and.callThrough();
const alertSpy = spyOn(window, 'alert');
const alertSpy = spyOn(alertService, 'showMessage');
fixture.detectChanges();

const submitButton = fixture.nativeElement.querySelector(
'button[type="submit"]'
);
const submitButton = fixture.nativeElement.querySelector('button[type="submit"]');
submitButton.click();
tick();

expect(alertSpy).toHaveBeenCalledWith('Preencha todos os campos corretamente!');
});
expect(alertSpy).toHaveBeenCalledWith('info', 'Alerta', 'Preencha todos os campos corretamente!');
}));

it('should call navigator method when "Esqueceu a senha?" is clicked', () => {
spyOn(component, 'navigator').and.callThrough();
const forgotPasswordLink =
fixture.nativeElement.querySelector('.text-gray-400');
const forgotPasswordLink = fixture.nativeElement.querySelector('.text-gray-400');
forgotPasswordLink.click();

expect(component.navigator).toHaveBeenCalledWith('/sendCodeResetPassword');

});

it('should call navigator method when "Cadastre-se" is clicked', () => {
spyOn(component, 'navigator').and.callThrough();
const registerLink =
fixture.nativeElement.querySelector('.text-blue-brand');
const registerLink = fixture.nativeElement.querySelector('.text-blue-brand');
registerLink.click();

expect(component.navigator).toHaveBeenCalledWith('/register');
});

it('should call login and return an error', () => {
it('should call login and handle error', fakeAsync(() => {
fixture.detectChanges();
const form = component.userForm;
form.setValue({ email: '[email protected]', password: 'password' });
const mySpy = spyOn(authService, 'loginUser').and.returnValue(throwError(() => new Error('Erro')));

const mySpy = spyOn(authService, 'loginUser').and.returnValue(throwError({ error: { message: 'Erro' } }));

component.login();
tick();

expect(mySpy).toHaveBeenCalled();
});
}));
});

0 comments on commit 86a2608

Please sign in to comment.