No tienes acceso a esta clase

隆Contin煤a aprendiendo! 脷nete y comienza a potenciar tu carrera

Aprende todo un fin de semana sin pagar una suscripci贸n 馃敟

Aprende todo un fin de semana sin pagar una suscripci贸n 馃敟

Reg铆strate

Comienza en:

0D
14H
18M
26S

Pruebas al login

22/25
Recursos

Aportes 3

Preguntas 0

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad?

o inicia sesi贸n.

Para los m茅todos que no retornan nada, cuando se quiere espiar una funci贸n, pero que no ejecute el m茅todo , se le pone en el spyOn el and.callThrough():

spyOn(tokenService, 'saveToken').and.callThrough()

Para que no me fallen los tests, he tenido que declarar as铆 la funci贸n del 鈥渆xpectOne鈥

    const request = httpController.expectOne({method: 'POST'});

para poder hacer pruebas al login es basicamente verificar el autentificador de Auth.service

auth.model.ts

export interface Auth {
聽 access_token: string;
}

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { switchMap, tap } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs';

import { environment } from './../../environments/environment';
import { Auth } from './../models/auth.model';
import { User } from './../models/user.model';
import { TokenService } from './../services/token.service';

@Injectable({
聽 providedIn: 'root'
})
export class AuthService {

聽 private apiUrl = `${environment.API_URL}/api/v1/auth`;
聽 private user = new BehaviorSubject<User | null>(null);
聽 user$ = this.user.asObservable();

聽 constructor(
聽 聽 private http: HttpClient,
聽 聽 private tokenService: TokenService
聽 ) {
聽 }

聽 getCurrentUser() {
聽 聽 const token = this.tokenService.getToken();
聽 聽 if (token) {
聽 聽 聽 this.getProfile()
聽 聽 聽 .subscribe()
聽 聽 }
聽 }

聽 login(email: string, password: string) {
聽 聽 return this.http.post<Auth>(`${this.apiUrl}/login`, {email, password})
聽 聽 .pipe(
聽 聽 聽 tap(response => this.tokenService.saveToken(response.access_token)),
聽 聽 );
聽 }

聽 getProfile() {
聽 聽 return this.http.get<User>(`${this.apiUrl}/profile`)
聽 聽 .pipe(
聽 聽 聽 tap(user => this.user.next(user))
聽 聽 );
聽 }

聽 loginAndGet(email: string, password: string) {
聽 聽 return this.login(email, password)
聽 聽 .pipe(
聽 聽 聽 switchMap(() => this.getProfile()),
聽 聽 )
聽 }

聽 logout() {
聽 聽 this.tokenService.removeToken();
聽 聽 this.user.next(null);
聽 }
}

auth.service.spec.ts

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { AuthService } from './auth.service';
import { TokenService } from './token.service';
import { Auth } from '../models/auth.model';
import { environment } from '../../environments/environment';

fdescribe('AuthService', () => {
聽 let authService: AuthService;
聽 let httpController: HttpTestingController;
聽 let tokenService: TokenService;

聽 beforeEach(() => {
聽 聽 TestBed.configureTestingModule({
聽 聽 聽 imports: [
聽 聽 聽 聽 HttpClientTestingModule
聽 聽 聽 ],
聽 聽 聽 providers: [
聽 聽 聽 聽 AuthService,
聽 聽 聽 聽 TokenService
聽 聽 聽 ]
聽 聽 });
聽 聽 authService = TestBed.inject(AuthService);
聽 聽 httpController = TestBed.inject(HttpTestingController);
聽 聽 tokenService = TestBed.inject(TokenService);
聽 });

聽 afterEach(() => {
聽 聽 httpController.verify();
聽 });

聽 it('should be create', () => {
聽 聽 expect(authService).toBeTruthy();
聽 });

聽 describe('test for login', () => {
聽 聽 it('should return a token', (doneFn) => {
聽 聽 聽 //Arrange
聽 聽 聽 const mockData: Auth = {
聽 聽 聽 聽 access_token: '121212'
聽 聽 聽 };
聽 聽 聽 const email = '[email protected]';
聽 聽 聽 const password = '1212';
聽 聽 聽 //Act
聽 聽 聽 authService.login(email, password).subscribe((data) => {
聽 聽 聽 聽 //Assert
聽 聽 聽 聽 expect(data).toEqual(mockData);
聽 聽 聽 聽 doneFn();
聽 聽 聽 });
聽 聽 聽 //http config
聽 聽 聽 const url = `${environment.API_URL}/api/v1/auth/login`;
聽 聽 聽 const req = httpController.expectOne(url);
聽 聽 聽 req.flush(mockData);
聽 聽 });
聽 });

聽 it('should call to saveToken', (doneFn) => {
聽 聽 //Arrange
聽 聽 const mockData: Auth = {
聽 聽 聽 access_token: '121212'
聽 聽 };
聽 聽 const email = '[email protected]';
聽 聽 const password = '1212';
聽 聽 spyOn(tokenService, 'saveToken').and.callThrough();
聽 聽 //Act
聽 聽 authService.login(email, password).subscribe((data) => {
聽 聽 聽 //Assert
聽 聽 聽 expect(data).toEqual(mockData);
聽 聽 聽 expect(tokenService.saveToken).toHaveBeenCalledTimes(1);
聽 聽 聽 expect(tokenService.saveToken).toHaveBeenCalledOnceWith('121212');
聽 聽 聽 doneFn();
聽 聽 });
聽 聽 //http config
聽 聽 const url = `${environment.API_URL}/api/v1/auth/login`;
聽 聽 const req = httpController.expectOne(url);
聽 聽 req.flush(mockData);
聽 });
});