0

have some errors with testing my website made with Angular. I do not have much experience in angular, I am getting this error whenever I try running my angular test.

This my login.component.spec.ts file looks like

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
import { DebugElement } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule, By } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CoreModule } from '../../core/core.module';
describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let de: DebugElement;
  let el: HTMLElement;
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [LoginComponent],
      imports: [
        CommonModule,
        BrowserModule,
        FormsModule,
        CoreModule,
        ReactiveFormsModule,
      ],
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(LoginComponent);
        let comp = fixture.componentInstance;
        de = fixture.debugElement.query(By.css('form'));
        el = de.nativeElement;
      });
  });
  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  fit(`should have’ as text ‘login page’`, () => {
    expect(component.title).toEqual('login page');
  });

  fit('should set’ submitted to true', () => {
    expect(component.submitted).toBeTruthy();
  });

  fit('should call the onSubmit method', () => {
    fixture.detectChanges();
    spyOn(component, 'onSubmit');
    el = fixture.debugElement.query(By.css('button')).nativeElement;
    el.click();
    expect(component.onSubmit).toHaveBeenCalledTimes(0);
  });

  fit('form should be invalid', () => {
    component.loginForm.controls['email'].setValue('');
    component.loginForm.controls['password'].setValue('');
    expect(component.loginForm.valid).toBeFalsy();
  });
  fit('form should be valid', () => {
    component.loginForm.controls['email'].setValue('asd@asd.com');
    component.loginForm.controls['password'].setValue('aAAada');
    expect(component.loginForm.valid).toBeTruthy();
  });
});

this is what my login.component.ts looks like

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../../core/services/auth.service';
import { first } from 'rxjs/operators';
import { ToastMessageService } from '../../shared/services/toast-message.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  isForgotPasswordView = false;
  passwordView = false;
  loginForm: FormGroup = this.formBuilder.group({
    email: ['', [Validators.required, Validators.email]],
    password: ['', Validators.required],
  });
  loading = false;
  submitted = false;
  returnUrl: string | undefined;
  showError: boolean = false;
  timeOutMessage: boolean = false;

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private authService: AuthService,
    private toastMessageService: ToastMessageService
  ) {}

  // convenience getter for easy access to form fields
  get f() {
    return this.loginForm.controls;
  }

  ngOnInit() {
    // get return url from route parameters or default to '/'
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || 'role';
    this.timeOutMessage = this.route.snapshot.queryParams['timeOut'];
  }

  onSubmit() {
    this.submitted = true;
    // stop here if form is invalid
    if (this.loginForm.invalid) {
      return;
    }
    this.loading = true;

    if (this.isForgotPasswordView) {
      const newPasswordPageUrl =
        window.location.origin + '/login/forgot_password';
      this.authService
        .forgotPassword(this.f?.email.value, newPasswordPageUrl)
        .pipe(first())
        .subscribe(
          () => {
            this.loading = false;
            this.toastMessageService.setToastMessage({
              delay: 3000,
              title: 'Successfully',
              type: 'success',
              message: 'New Password link has sent to email',
            });
            this.isForgotPasswordView = false;
          },
          () => {
            this.showError = true;
            this.loading = false;
          }
        );
    } else {
      this.authService
        .login(this.f?.email.value, this.f?.password.value)
        .pipe(first())
        .subscribe(
          (result) => {
            if (
              this.returnUrl === 'role' &&
              this.authService.currentUserValue?.active
            ) {
              this.router.navigate([
                this.authService.currentUserValue?.userRoles![0].role?.role,
              ]);
            } else if (this.authService.currentUserValue?.active == false) {
              this.router.navigate(['login/reset_password']);
            } else {
              this.router.navigate([this.returnUrl]);
            }
          },
          () => {
            this.showError = true;
            this.loading = false;
          }
        );
    }
  }

  openForgotPasswordPage() {
    this.isForgotPasswordView = true;
  }

  title() {}
}

I don't know I am this getting errors NullInjectorError: R3InjectorError(DynamicTestModule)[ActivatedRoute -> ActivatedRoute]: NullInjectorError: No provider for ActivatedRoute! TypeError: Cannot read properties of undefined (reading '')

Aminson
  • 1
  • 1
  • 1
  • Does this answer your question? [Angular 7 Test: NullInjectorError: No provider for ActivatedRoute](https://stackoverflow.com/questions/53654341/angular-7-test-nullinjectorerror-no-provider-for-activatedroute) – R. Richards Dec 05 '21 at 21:45
  • I got the first part done but still have questions about:- should have’ as text ‘login’, should set’ submitted to true, should call the onSubmit method – Aminson Dec 05 '21 at 22:06
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Dec 09 '21 at 11:30

0 Answers0