Getting "Expected undefined to be truthy." when testing to see if Componet is create

Viewed 1977

As part of expanding and updating my Skill set. I have been assigned to write Jasmine/Karma tests for an Angular 9 application. I have completed an online tutorial and done some Google searches. I started writing my first unguided test cases and I am running into something I have not yet found a way past.

My HTML is this:

<div class="container-fluid">
<div class="center">
  <div class="welcome-container">
    <div class="title">PCPlan</div>
  </div>
  <mat-card>
    <div class="login-form">
      <div class="inputs">
        <mat-form-field class="formfield-min-width">
          <input matInput type="text" placeholder="AD Username" [(ngModel)]="model.username" (keyup.enter)="login()" tabindex="0" autofocus="true"/>
          <button mat-button *ngIf="model.username" matSuffix mat-icon-button aria-label="username" (click)="model.username=''" tabindex="-1">
            <i class="fas fa-times-circle"></i>
          </button>
        </mat-form-field>

        <mat-form-field class="formfield-min-width">
          <input matInput type="password" placeholder="Password" [(ngModel)]="model.password" (keyup.enter)="login()" tabindex="0" autofocus="true"/>
          <button mat-button *ngIf="model.password" matSuffix mat-icon-button aria-label="password" (click)="model.password=''" tabindex="-1">
            <i class="fas fa-times-circle"></i>
          </button>
        </mat-form-field>
      </div>

      <button mat-raised-button color="primary" (click)="login()" class="login-button">LOG IN</button>

      <div>
        <div *ngIf="errMsg" style="color:indianred; font-weight: bold">{{errMsg}}</div>
      </div>

    </div>
  </mat-card>
</div>

My .ts file is:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthGuard } from 'src/app/routing/guards/auth.guard';
import { AuthenticationService } from 'src/app/services/shared/authentication.service';
import { LoginService } from 'src/app/services/shared/login.service';
//import { UserAPI } from 'src/app/services/api/userAPI.service';
import { take } from 'rxjs/operators';
import { authBaseUrl, pcplanServiceBaseUrl } from 'src/environments/environment';
//import { MatToolbarModule, MatIconModule, MatFormFieldModule, MatCardModule, MatInputModule, MatButtonModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { CdkTableModule} from '@angular/cdk/table';
import {DataSource} from '@angular/cdk/table';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})

export class LoginComponent implements OnInit {
  model: any = {
    username: '',
    password: '',
  };
  errMsg = '';
  constructor(
    private router: Router,
    private loginService: LoginService,
    private authenticationService: AuthenticationService,
   // public userAPI: UserAPI,
    public Authinacate: AuthGuard,
    private http: HttpClient,
  ) { }
  userInfo = this.authenticationService.getUserInfo();
  userInTestTableValue = '';
  userAccessChecked = false;

  ngOnInit() {
    // reset login status
    console.log("Initializing: login.component.ts")


    this.loginService.logout();
  }

  login() {
    this.loginService.getToken(this.model.username, this.model.password)
      .subscribe(resp => {
        if (!resp.user || resp.user.token === 'INVALID') {
          console.log(":(");
          if (!Array.isArray(resp)) {
            this.errMsg = 'Username or password is incorrect ';
          }
          return;
        } 
        else {
          console.log('success')
          this.router.navigate([resp.landingPage]);
        }
      },
        errResponse => {
          switch (errResponse.status) {
            case 401:
              this.errMsg = 'Username or password is incorrect';
              console.log(this.errMsg);
              break;
            case 404:
              this.errMsg = 'Service not found';
              break;
            case 408:
              this.errMsg = 'Request Timedout';
              break;
            case 500:
              this.errMsg = 'Internal Server Error';
              break;
            default:
              this.errMsg = 'Login failed: Make sure Username and Password are correct and try again.';
          }
        }
      );
  }

  onSignUp() {
    this.router.navigate(['signup']);
  }
}

and my spec file is:

import { ComponentFixture, TestBed } from "@angular/core/testing"
import { LoginComponent } from './login.component'

describe('Login Component', () => {
    let fixture: ComponentFixture<LoginComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [LoginComponent],
        });
        fixture = TestBed.createComponent(LoginComponent);
    });

    it('Component successfully created', () => {
        expect(fixture).toBeTruthy();
    });
})

My suspicion is that there is something simple that I am missing, but I can't get this test to run and the result I am getting "Expected undefined to be truthy."

I believe the fixture is defined.

1 Answers

I figured out that the actual code I was testing was more complex then the tutorials I had been doing up to this point. Once I got everything in the constructor mocked in the beforeEach I am no longer getting this error.

I do want to thank the user hugomosh because his comment lead me to finding the answer this morning.

Related