【问题标题】:Expected undefined to be defined error in Karma unit testing while testing a function using .toBeTruthy()使用 .toBeTruthy() 测试函数时,预期在 Karma 单元测试中定义未定义错误
【发布时间】:2019-12-10 01:24:38
【问题描述】:

在下面的规范文件中,我涵盖了 saveAdmin 功能的测试用例,但出现了下面提到的错误

Expected undefined to be defined 在使用 .toBeTruthy() 测试函数时在 Karma 单元测试中出现错误,我已经给出了 ts 文件和 spec 文件也提到了来自 karma 的错误。在此先感谢

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 => {});
      }
      /**
       * This method will run will save is clicked.
       * */
      saveAdmin(){
        this.checkBoxSelected = true;
        this.accessHasSelected = this.adminObj.access.filter(t=>{
          if(this.checkBoxSelected){
            if(t.selected){this.checkBoxSelected = false;}
            else if(t.access !== null){
              t.access.filter(x=>{
                if(x.selected) {this.checkBoxSelected = false;}
              })
            }
          }
        });
        if(!this.checkBoxSelected) {
          this.dataService.saveAdmin(this.adminObj, this.data.isNew).subscribe(
            response => {
              //component related success actions
              this.dialogRef.addPanelClass('close-modal');
              setTimeout(() => {
                this.dialogRef.close({
                  data: response
                });
              }, 500);
            },
            error => {
              this.errorObj = {};
              //component related error actions
              for (var v in error.error.errors) {
                this.errorObj[error.error.errors[v].field] = error.error.errors[v].messageId;
              }
            });
        }else{
            this.errorObj.access = "requiredAccessError";
          }
      }
      /**
       *
       */
      ngOnInit() {}
      onModalCancel(): void {
        this.dialogRef.addPanelClass('close-modal');
        setTimeout(()=>{
          this.dialogRef.close();
        },500);
      }
    }

规格文件:

import { AdminDialogComponent } from "./admin-dialog.component";
import { TestBed, ComponentFixture,async,inject  } 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: {} },
        {
          provide: MAT_DIALOG_DATA, useValue: {
            isNew: false, // I guess it's boolean
            adminObj: {firstName: "AAAAAA", lastName: "AA", password: null, emailId: "test@test.com",
              access : [
                {
                  accessCode: 1,
                  accessName: 'test',
                  path: '/admin/tests',
                  orderBy: 5,
                  access: []
                },
                {
                  accessCode: 3,
                  accessName: 'view-aep-org',
                  path: '/admin/testing',
                  orderBy: 1,
                  access: []
                }]
            }
          }
        },
        {provide: dataService, useValue: {}}
      ],
      schemas: [NO_ERRORS_SCHEMA]
  });
    TestBed.overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [AdminDialogComponent]
      }
    });

    TestBed.compileComponents();

    // create component and test fixture
    fixture = TestBed.createComponent(AdminDialogComponent);

    // get test component from the fixture
    component = fixture.componentInstance;
   // component.ngOnInit();
  });
  beforeEach(inject([MatDialog, OverlayContainer],
    (d: MatDialog, oc: OverlayContainer) => {
      dialog = d;
      overlayContainer = oc;
    })
  );
  afterEach(() => {
    overlayContainer.ngOnDestroy();
  });
  it('should create', () => {
    expect(component).toBeTruthy();
  });
  it('saveAdmin for requiredAccessError ', () => {
    component.adminObj = {firstName: "AAAAAA", lastName: "AA", password: null, emailId: "test@test.com",
      access : [
        {
          access: null,
          accessCode: 1,
          accessName: "test",
          active: true,
          orderBy: 1,
          parentAccessCode: null,
          path: "/test/test",
          selected: false,
          showCheckbox: true
        }]
    };
    expect(component.saveAdmin()).toBeTruthy();
  });

});

错误:

Component: admin-dialog > saveAdmin for requiredAccessError
Expected undefined to be defined.
Error: Expected undefined to be defined.
    at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/dashboard/manage-admin/admin-dialog/admin-dialog.component.spec.ts:150:35)

【问题讨论】:

    标签: angular typescript unit-testing karma-jasmine


    【解决方案1】:

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

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

    it("saveAdmin for requiredAccessError", () => {
          expect(component.saveAdmin).toBeDefined();
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 2015-06-29
      • 2014-03-22
      相关资源
      最近更新 更多