【问题标题】:Error: Expected undefined to be truthy. KARMA JASMINE unit test case for angular 8错误:预期未定义是真实的。角度 8 的 KARMA JASMINE 单元测试用例
【发布时间】:2019-12-10 18:49:48
【问题描述】:

在 Angular 8 中运行 karma jasmine 单元测试用例时出现以下错误

组件:管理对话框 > onModalCancel 错误:预期未定义是真实的。

我提供了我的规范和打字稿文件。请提出为什么期望未定义是真实的。提前合适

规格文件

import { AdminDialogComponent } from "./admin-dialog.component";
import {TestBed, ComponentFixture, async, inject, tick, fakeAsync} from '@angular/core/testing';
import { FormsModule } from "@angular/forms";
import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';
import {TranslateModule,TranslateService} from "@ngx-translate/core";
import {Inject, NO_ERRORS_SCHEMA} from "@angular/core";
import {MAT_DIALOG_DATA, MatDialog, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
import { OverlayContainer } from '@angular/cdk/overlay';
import {HttpClientModule} from "@angular/common/http";
import {RouterTestingModule} from "@angular/router/testing";
import {DataService} from "../../../services/data.service";
import {of} from "rxjs/internal/observable/of";

describe('Component: admin-dialog', () => {

  let component: AdminDialogComponent;
  let fixture: ComponentFixture<AdminDialogComponent>;
  let translate: TranslateService;
  let dialog: MatDialog;
  let overlayContainer: OverlayContainer;
  let dataService: DataService;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule, MatDialogModule, HttpClientModule,RouterTestingModule,TranslateModule.forRoot()],
      declarations: [AdminDialogComponent],
      providers: [TranslateService,
        { provide: MatDialogRef, useValue: {addPanelClass: ()=>{'close-modal'} }},
        {
          provide: MAT_DIALOG_DATA, useValue: {
            isNew: false, // I guess it's boolean
            adminObj: {firstName: "AAAAAA", lastName: "AA", password: null, emailId: "test@test.com"}
          }
        },
        {provide: dataService, useValue: {}}
      ],
      schemas: [NO_ERRORS_SCHEMA]
  });
    TestBed.overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [AdminDialogComponent]
      }
    });
    TestBed.compileComponents();
    fixture = TestBed.createComponent(AdminDialogComponent);
    component = fixture.componentInstance;
  });
  beforeEach(inject([MatDialog, OverlayContainer],
    (d: MatDialog, oc: OverlayContainer) => {
      dialog = d;
      overlayContainer = oc;
    })
  );
  afterEach(() => {
    overlayContainer.ngOnDestroy();
  });
  it('should create', () => {
    expect(component).toBeTruthy();
  });
  it("onModalCancel", () => {
      expect(component.onModalCancel()).toBeTruthy();
  });

});

Ts 文件

import {Component, Inject, OnInit} from "@angular/core";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
import {DataService} from "../../../services/data.service";
@Component({
  selector: 'admin-dialog',
  templateUrl: './admin-dialog.component.html',
  styleUrls: ['./admin-dialog.component.scss']
})
export class AdminDialogComponent implements OnInit {
  public accessHasSelected : any ='';
  public errorObj : any = {};
  public checkBoxSelected : boolean;
  public adminObj: any = {
    active:true,
    firstName:"",
    lastName:"",
   // emailId:"",
    access:[]
  };
  /***
   *
   * @param dialogRef
   * @param data
   * @param fromGroup
   * @param dataService
   */
  constructor(
    public dialogRef: MatDialogRef<AdminDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private dataService: DataService) {

    if (this.data.isNew){
      this.newAdmin();
    }
    else {
      this.editAdmin(this.data.adminObj);
    }
  }
  /*
  * This method will get called while loading new admin modal.
  * */
  newAdmin() {
    this.dataService.getAllAdminAccess().subscribe(
      response => {
        this.adminObj.access = response.access;
      },
      error => { });
  }
  /***
   * This method will get called while loading edit existing admin modal.
   * @param response
   */
  editAdmin(response){
    console.log(response);
    this.dataService.getAdminDetails(response.emailId).subscribe(
      response => {
        //component related success actions
        this.adminObj = response;
      },
      error => {});
  }
  /**
   *
   */
  ngOnInit() {}
  onModalCancel(): void {
    this.dialogRef.addPanelClass('close-modal');
    setTimeout(()=>{
      this.dialogRef.close();
    },500);
  }
}

【问题讨论】:

  • @Buczkowski 你能帮我吗
  • 你为什么要像返回布尔值一样测试 void 函数?
  • @Alexus 如何覆盖onModalCancel()的测试用例

标签: angular typescript unit-testing karma-jasmine


【解决方案1】:

ngOnInit() 没有返回任何值。因此它显示未定义。

要检查函数是否已定义,您可以编写如下测试用例:

it("onModalCancel", () => {
      expect(component.onModalCancel).toBeDefined();
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-09
    • 2019-12-10
    • 1970-01-01
    • 2018-06-07
    • 2015-06-29
    • 2020-05-30
    • 2015-03-23
    • 1970-01-01
    相关资源
    最近更新 更多