Получение «Ожидается, что неопределенное значение будет правдой». при тестировании, чтобы увидеть, создается ли Comp onet - PullRequest
1 голос
/ 09 июля 2020

В рамках расширения и обновления моего набора навыков. Мне поручили написать тесты Jasmine / Karma для приложения Angular 9. Я закончил онлайн-руководство и выполнил поиск в Google. Я начал писать свои первые неуправляемые тестовые примеры и столкнулся с чем-то, что еще не нашел решения.

Мой HTML это:

<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>

Мой файл .ts :

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']);
  }
}

и мой файл spe c:

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();
    });
})

У меня есть подозрение, что мне не хватает чего-то простого, но я не могу пройти этот тест run, и в результате я получаю «Ожидается, что undefined будет правдой».

Я считаю, что прибор определен.

1 Ответ

0 голосов
/ 09 июля 2020

Я понял, что реальный код, который я тестировал, был более сложным, чем уроки, которые я делал до этого момента. Как только я получил все в конструкторе, высмеянный в beforeEach, я больше не получаю эту ошибку.

Я хочу поблагодарить пользователя hugomo sh, потому что его комментарий заставил меня найти ответ сегодня утром.

...