Angular 12 Unit testing

I am struggling to figure out how to write unit tests for this specific function.


  loginUser(): void {
    this.formSubmitted = true;

    if (!this.signinFormValueEmpty() && this.passwordValueMeetsValidation()) {
      this.authService.userLogin(this.signInForm.value)?.subscribe(
        () => {
          this.router.navigate(['/dashboard']);
        },
        (err: HttpErrorResponse) => {
          this.hasErrors = true;

          if (err.status === 400) {
            this.errorString = 'The username and/or password you have entered are incorrect.';
          } else if (err.status === 500) {
            this.errorString = 'Something unexpected happened';
          }
        }
      );
    }
  }

I`ve tried something like this, but I am not sure what I have to mock

import { AuthService } from './../services/auth.service';
import { HttpClient } from '@angular/common/http';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';

import { LoginComponent } from './login.component';


describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  const httpClientSpy: jasmine.SpyObj<HttpClient> = jasmine.createSpyObj('httpClient', ['post']);
  const formBuilder: FormBuilder = new FormBuilder();
  let authService: AuthService;
  const routerSpy = {
    navigate: jasmine.createSpy('navigate'),
  };

  const authServiceStub: jasmine.SpyObj<AuthService> = jasmine.createSpyObj('authService', ['userLogin']);

  httpClientSpy.post.and.returnValue(of({}));

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [LoginComponent],
      imports: [
        RouterTestingModule,
        FormsModule,
        ReactiveFormsModule.withConfig({ warnOnNgModelWithFormControl: 'never' }),
      ],
      providers: [
        AuthService,
        { provide: HttpClient, useValue: httpClientSpy },
        { provide: FormBuilder, useValue: formBuilder },
        { provide: Router, useValue: routerSpy },
      ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    authService = TestBed.inject(AuthService);
    fixture.detectChanges();
  });

I tried to spy on userLogin method but I got the error Expected spy userLogin to have been called. What I am doing wrong? how should I get inside the subscribe block?

  it('should subscribe method inside loginUser is being called', fakeAsync(() => {
    let loginResult = '';
    let userSpy = spyOn(authService, 'userLogin').and.returnValue(of(loginResult)).and.callThrough();

    fixture.componentInstance.loginUser();
    tick();
    //expect(userSpy).toHaveBeenCalledBefore(subSpy);
    expect(userSpy).toHaveBeenCalled();
  }));

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.