Angular Login Component, Service and UnitTesting

January 5, 2023 · 8 min readLucian Ciobanu
Tags:AngularUnitTest

Hello 2023, let's have some fun!

My first post for this year is the template and logic behind a login screen in angular and the related logic we've added to prevent the user from navigating to pages they should not see without being logged in and a simple cache to assist the devs in not having to login everytime when they develop something.

app.routing.module

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', canActivate: [AuthGuard], canDeactivate: [PendingChangesGuard], component: HomeComponent}
  { path: '', redirectTo: '/login', pathMatch: 'full'}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

auth.guard.ts

export class AuthGuard implements CanActivate {
  
  public canVisit: boolean;

  canActivate(): boolean {
    this.loginService.$login.subscribe(login => {
      this.canVisit = login.Success;
    });
    
    if (this.canVisit) {
      return true;
    } else {
      this.router.navigateByUrl('/login');
      return false;
    }
  }
}

cand-deactivate-guard.ts

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean | Observable<boolean>;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    return component.canDeactivate() ?
      true :
      confirm('There are unsaved changes. Are you sure you want to leave?');
  }
}

To implement the pending changes guard, you also need to add it the component's export class as: "implements ComponentCanDeactivate" right after OnInit or OnDestroy.

login.component.html

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
  <mat-form-field>
    <mat-label>User Name</mat-label>
    <input type="text" matInput formControlName="username" [errorStateMatcher]="matcher">
    <mat-error *ngIf="loginForm.get('username')?.hasError('required')">
      Please Enter a Username
    </mat-error>
  </mat-form-field>
  <mat-form-field>
    <mat-label>Password</mat-label>
    <input type="password" matInput formControlName="password" [errorStateMatcher]="matcher">
    <mat-error *ngIf="loginForm.get('password')?.hasError('required')">
      Please Enter a Password
    </mat-error>
  </mat-form-field>
  <mat-error *ngIf="loginForm.errors">
    <div *ngIf="loginForm.errors.invalidLogin">
      <p>Incorrect Username or Password</p>
    </div>
  </mat-error>
  <button type="submit mat-flat-button [disbled]="isLoading>Log In</button>
</form>

<mat-spinner *ngIf="isLoading"></mat-spinner>

login.component.ts

export class LoginComponent implements OnDestroy {
  public loginForm: FormGroup;
  public matcher = new CustomErrorStateMatcher();
  public isLoading: boolean = false;
  private subscriptions: Subscription[] = [];

  constructur(private fb: FormBuilder, private loginService: LoginService, private router: Router) {
    this.loginForm = this.fb.group({
      username: ['', Validators.required],
      password: ['', Validators. required[
    })
  }
                                   
  ngOnInit(): void {
      if (environment.devOnly) {
        let lastUrl = sessionStorage.getItem('lastUrl');
        if (lastUrl) {
          let sessionLogin = sessionStorage.getItem('lastUrl');
          let tempTimestamp = moment(login.LoginTime).add(1, 'day');
          const today = moment();
          const needToReLogin = moment(tempTimestamp).isBefore(moment(today));
          if (!needToReLogin) {
            this.loginService.login$.next(login);
            this.router.navigateByUrl(lastUrl);
          }
        }
      } else {
        sessionStorage.setItem('lastUrl', '/home');
      }
    }
  }
  
  ngOnDestroy(): void {
    this.subscriptions.forEach(subscription => {
      subscription.unsubscribe();
    });
  }
  
  onSubmit(): void {
    if (this.loginForm.valid) {
      this.isLoading = true;
      const credentials: LoginCredentials = {
        Password: this.loginForm.get('password')?.value,
        Username: this.loginForm.get('username')?.value
      }
      
      const loginSubscription = this.loginService.login(credentials).subscribe(
        result => {
          if (!result.Success) {
            this.loginForm.setErrors({ invalidLogin: true });
          }
          this.isLoading = false;
        },
        error => {
          this.isLoading = false;
        }
      )
      this.subscriptions.push(loginSubscription);
    }
  }
}

login.component.spec.ts

const credentialsMock: LoginCredentials = {
  Password: 'string',
  Username: 'string'
}

class LoginServiceMock {
  $login: BehaviorSubject<Login> = new BehaviorSubject<Login>({
    LoginTime: '',
    Message: '',
    User: {
      UserID: '',
      UserName: '',
    }
  });
  
  login() {
    return of();
  }
}

describe('LoginComponent', () => {
  let component: LoginComponent;
  let loginService: LoginService;
  let fixture: ComponentFixture<LoginComponent>;
  
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes([{path: 'home', component: HomeComponent}]), HttpClientTestingModule],
      declarations: [LoginComponent, HomeComponent],
      providers: [
        { provide: LoginService, useClass: LoginServiceMock }
      ]
    })
      .compileComponents();
  });
  
  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    loginServie = TestBed.inject(LoginService);
    fixture.detectChanges();
  });
  
  it('should get login credentials from cache', () => {
    environment.devOnly = true;
    sessionStorage.setItem('lastUrl', '/home');
    sessionStorage.setItem('login', JSON.stringify(loginMock));
    component.ngOnInit();
    expect(sessionStorage.getItem('login').toEqual(JSON.stringify(loginMock));
  }
     
  it('should login successfully', () => {
    spyOn(loginService, 'login').and.returnValue(of(loginMock));
    component.loginForm.controls.username.setValue('test');
    component.loginForm.controls.password.setValue('pass');
    component.ngOnInit();
    expect(loginService.login).toHaveBeenCalled();
    loginService.login(credentialsMock).subscribe(result => {
      expect(result.Success).toEqual(true);
    });
  });
});

login.service.ts

public $login: BehaviorSubject<Login> = new BehaviorSubject<Login>({
  LoginTime: '',
  User: {
    UserID: '',
    UserName: ''
  }
});

public login(credentials: LoginCredentials) {
  return this.http.post<Login>(environment.apiUrl + '/Login', credentials)
    .pipe(
      tap(login => {
        if (environment.devOnly) {
          sessionStorage.setItem('login', JSON.stringify(login));
          sessionStorage.setItem('lastUrl', '/home');
        }
        if (login.Success) {
          this.router.navigateByUrl('/home');
        }
        this.$login.next(login);
      })
    );
  }
}

error-state-matcher.ts

export class CustomErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control & control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

So this is a far from basic example which I find very useful!

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery