Angular Karma - nb-card-header' 不是已知元素

Posted

技术标签:

【中文标题】Angular Karma - nb-card-header\' 不是已知元素【英文标题】:Angular Karma - nb-card-header' is not a known elementAngular Karma - nb-card-header' 不是已知元素 【发布时间】:2020-11-17 20:42:33 【问题描述】:

当我尝试使用 karma 进行测试时,我在许多页面中都收到此错误....

Failed: Template parse errors:
'nb-card-header' is not a known element:
1. If 'nb-card-header' is an Angular component, then verify that it is part of this module.
2. If 'nb-card-header' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("<nb-card>
  [ERROR ->]<nb-card-header>
      Manage Coupon
  </nb-card-header>
"): ng:///DynamicTestModule/EditCouponComponent.html@1:2
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("e">
                    <input type="text" placeholder="Coupon Name" class="form-control" id="usr" [ERROR ->][(ngModel)]="CouponDetails.name">
                </div>
            </div>
"): ng:///DynamicTestModule/EditCouponComponent.html@12:95
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("">
                    <input type="text" placeholder="Description" class="form-control" id="usr2" [ERROR ->][(ngModel)]="CouponDetails.description">
                </div>
            </div>
"): ng:///DynamicTestModule/EditCouponComponent.html@19:96
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("                       <input type="text" placeholder="Coupon Code" class="form-control" id="stuff" [ERROR ->][(ngModel)]="CouponDetails.code" (keydown)="onKeydown($event)">
                    </span>
       "): ng:///DynamicTestModule/EditCouponComponent.html@27:101
Can't bind to 'ngModel' since it isn't a known property of 'select'. ("     <div class="profile-info-value">
                    <span> 
                        <select [ERROR ->][(ngModel)]="CouponDetails.status" class="browser-default custom-select" placeholder="Select Status">"): ng:///DynamicTestModule/EditCouponComponent.html@35:32
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("                            <input matInput (ngModelChange)="changeMaxDate($event)" [min]="minDate" [ERROR ->][(ngModel)]="CouponDetails.startDate" [matDatepicker]="picker" placeholder="Choose a Promotion Start "): ng:///DynamicTestModule/EditCouponComponent.html@47:100
Can't bind to 'matDatepicker' since it isn't a known property of 'input'. ("Input (ngModelChange)="changeMaxDate($event)" [min]="minDate" [(ngModel)]="CouponDetails.startDate" [ERROR ->][matDatepicker]="picker" placeholder="Choose a Promotion Start Date" >
                            <"): ng:///DynamicTestModule/EditCouponComponent.html@47:138
Can't bind to 'htmlFor' since it isn't a known property of 'mat-datepicker-toggle'.
1. If 'mat-datepicker-toggle' is an Angular component and it has 'htmlFor' input, then verify that it is part of this module.
2. If 'mat-datepicker-toggle' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("der="Choose a Promotion Start Date" >
                            <mat-datepicker-toggle matSuffix [ERROR ->][for]="picker"></mat-datepicker-toggle>
                            <mat-datepicker #picker></mat-da"): ng:///DynamicTestModule/EditCouponComponent.html@48:61
'mat-datepicker-toggle' is not a known element:
1. If 'mat-datepicker-toggle' is an Angular component, then verify that it is part of this module.
2. If 'mat-datepicker-toggle' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[matDatepicker]="picker" placeholder="Choose a Promotion Start Date" >
                            [ERROR ->]<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                           "): ng:///DynamicTestModule/EditCouponComponent.html@48:28
'mat-datepicker' is not a known element:
1. If 'mat-datepicker' is an Angular component, then verify that it is part of this module.
2. If 'mat-datepicker' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("at-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                            [ERROR ->]<mat-datepicker #picker></mat-datepicker>
                        </mat-form-field>
               "): ng:///DynamicTestModule/EditCouponComponent.html@49:28
'mat-form-field' is not a known element:
1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("             <div class="profile-info-value">
                    <span> 
                        [ERROR ->]<mat-form-field>
                            <input matInput (ngModelChange)="changeMaxDate($event)""): ng:///DynamicTestModule/EditCouponComponent.html@46:24
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("                    <mat-form-field>
                            <input matInput [min]="minDate2"  [ERROR ->][(ngModel)]="CouponDetails.endDate" [matDatepicker]="pickers" placeholder="Choose Expiration Date">
"): ng:///DynamicTestModule/EditCouponComponent.html@59:62
Can't bind to 'matDatepicker' since it isn't a known property of 'input'. ("
                            <input matInput [min]="minDate2"  [(ngModel)]="CouponDetails.endDate" [ERROR ->][matDatepicker]="pickers" placeholder="Choose Expiration Date">
                            <mat-dat"): ng:///DynamicTestModule/EditCouponComponent.html@59:98
Can't bind to 'htmlFor' since it isn't a known property of 'mat-datepicker-toggle'.
1. If 'mat-datepicker-toggle' is an Angular component and it has 'htmlFor' input, then verify that it is part of this module.
2. If 'mat-datepicker-toggle' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("placeholder="Choose Expiration Date">
                            <mat-datepicker-toggle matSuffix [ERROR ->][for]="pickers"></mat-datepicker-toggle>
                            <mat-datepicker #pickers></mat-"): ng:///DynamicTestModule/EditCouponComponent.html@60:61
'mat-datepicker-toggle' is not a known element:
1. If 'mat-datepicker-toggle' is an Angular component, then verify that it is part of this module.
2. If 'mat-datepicker-toggle' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("dDate" [matDatepicker]="pickers" placeholder="Choose Expiration Date">
                            [ERROR ->]<mat-datepicker-toggle matSuffix [for]="pickers"></mat-datepicker-toggle>
                          "): ng:///DynamicTestModule/EditCouponComponent.html@60:28
'mat-datepicker' is not a known element:
1. If 'mat-datepicker' is an Angular component, then verify that it is part of this module.
2. If 'mat-datepicker' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("t-datepicker-toggle matSuffix [for]="pickers"></mat-datepicker-toggle>
                            [ERROR ->]<mat-datepicker #pickers></mat-datepicker>
                        </mat-form-field>
              "): ng:///DynamicTestModule/EditCouponComponent.html@61:28
'mat-form-field' is not a known element:
1. If 'mat-form-field' is an Angular component, then verify that it is part of this module.
2. If 'mat-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("             <div class="profile-info-value">
                    <span> 
                        [ERROR ->]<mat-form-field>
                            <input matInput [min]="minDate2"  [(ngModel)]="CouponDe"): ng:///DynamicTestModule/EditCouponComponent.html@58:24
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("="number" (keypress)="numberOnly($event)" placeholder="Usage Limit" class="form-control" id="stuff" [ERROR ->][(ngModel)]="CouponDetails.usageLimit">
                    </span>
                </div>
"): ng:///DynamicTestModule/EditCouponComponent.html@71:143
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("  (keypress)="numberOnly($event)" placeholder="Discount Percentage" class="form-control" id="stuff" [ERROR ->][(ngModel)]="CouponDetails.offerPercentage">
                    </span>
                </div>
"): ng:///DynamicTestModule/EditCouponComponent.html@80:161
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("(keypress)="numberOnly2($event)" placeholder="Minimum Order Amount" class="form-control" id="stuff" [ERROR ->][(ngModel)]="CouponDetails.minimumOrderAmount">
                        <label for="stuff" class=" i"): ng:///DynamicTestModule/EditCouponComponent.html@89:153
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("ypress)="numberOnly2($event)" placeholder="Maximum Discount Amount" class="form-control" id="stuff" [ERROR ->][(ngModel)]="CouponDetails.maximumLimit">
                        <label for="stuff" class=" input-i"): ng:///DynamicTestModule/EditCouponComponent.html@99:156
'nb-card-body' is not a known element:
1. If 'nb-card-body' is an Angular component, then verify that it is part of this module.
2. If 'nb-card-body' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
  </nb-card-header>

  [ERROR ->]<nb-card-body>
        <div class="profile-user-info" *ngIf="CouponDetails">
                
"): ng:///DynamicTestModule/EditCouponComponent.html@5:2
'nb-card' is not a known element:
1. If 'nb-card' is an Angular component, then verify that it is part of this module.
2. If 'nb-card' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
        </div>
  </nb-card-body>
[ERROR ->]<nb-card>"): ng:///DynamicTestModule/EditCouponComponent.html@119:0
'nb-card' is not a known element:
1. If 'nb-card' is an Angular component, then verify that it is part of this module.
2. If 'nb-card' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]<nb-card>
  <nb-card-header>
      Manage Coupon
"): ng:///DynamicTestModule/EditCouponComponent.html@0:0

组件

import  Component, OnInit, ElementRef, ViewChild  from '@angular/core';
import  ApiService  from '../../../../app/services/api.service';
import  ToasterConfig  from 'angular2-toaster';
import  Router, ActivatedRoute  from '@angular/router';
import  NbComponentStatus, NbGlobalPhysicalPosition, NbToastrService from '@nebular/theme';
import  AuthService  from '../../../services/auth.service';
import  UploadFileService  from '../../../services/upload-file.service';
import  EnvironmentService  from '../../../../environments/environment.service';
import  NgxSpinnerService  from "ngx-spinner";
import  NgbModal,ModalDismissReasons, NgbModalConfig  from '@ng-bootstrap/ng-bootstrap';
import  FormBuilder, FormGroup, FormArray, AbstractControl  from '@angular/forms';
import 'rxjs/add/operator/debounceTime';

export interface Item

  teaType:string;
  noOfContainers:number;
  weightPerContainerinKgs:number;
  totalItemWeight:number
      

@Component(
  selector: 'ngx-edit-menu',
  templateUrl: './edit-coupon.component.html',
  styleUrls: ['./edit-coupon.component.scss']
)

export class EditCouponComponent implements OnInit   
  minDate: any;
  minDate2: any;
  CouponDetails: any;
  currency:any;
  constructor(private apiService: ApiService,
    private auth: AuthService,
    private toastrService: NbToastrService,
    private router: Router,
    private uploadService:UploadFileService,
    public envService: EnvironmentService,
    private spinner: NgxSpinnerService,
    private modalService: NgbModal,
    private fb: FormBuilder,
    private route: ActivatedRoute) 
      if(localStorage.getItem('CouponId'))
        this.getCouponById(localStorage.getItem('CouponId'));
       else 
        this.getCoupon();
      
          
        
  
 
  ngOnInit()       
    this.getStatus(); 
    this.minDate = new Date();
    this.currency =localStorage.getItem('CurrencySymbol');
  

  changeMaxDate(date)
    this.minDate2 = date;
    if(this.CouponDetails.endDate)
      if(new Date(this.CouponDetails.endDate) < new Date(this.minDate2))
        this.CouponDetails.endDate = null;
        this.showToast('danger', '', 'Please Select Expiry Date');
      
      
    

  

  getCoupon() 
    this.CouponDetails =  
      name: "", 
      description:"", 
      code: "", 
      status: "", 
      startDate: "", 
      endDate: "", 
      offerPercentage: "", 
      usageLimit: "", 
      minimumOrderAmount: "",
      maximumLimit : "",
    ; 
    this.minDate2 = new Date();
  

  getCouponById(CouponId)
    this.apiService.getCouponById(CouponId).subscribe((res)=>
      const data = res.body.discountCodes;
      this.CouponDetails = data;
      this.minDate2 = data.startDate;
    );
  

  status: any;
  public getStatus()
    this.status = [
       value: 'active', label: 'Active' ,
       value: 'inactive', label: 'Inactive' ,
    ];
  

  public savedetails()
    if(!this.CouponDetails.name || !this.CouponDetails.code || !this.CouponDetails.status 
      || !this.CouponDetails.startDate || !this.CouponDetails.endDate || !this.CouponDetails.usageLimit
      || !this.CouponDetails.offerPercentage || !this.CouponDetails.minimumOrderAmount 
      || !this.CouponDetails.maximumLimit)
        this.showToast('danger', '', 'Please fill the mandatory fields.');
        return;
    
    if(this.CouponDetails.offerPercentage > 99)
      this.showToast('danger', '', 'Offer percentage should not be greater than 99%.');
        return;
    
    if(this.CouponDetails.minimumOrderAmount < this.CouponDetails.maximumLimit)
      this.showToast('danger', '', 'Maximum discount amount should not be greater than Minimum order amount.');
        return;
    
    this.spinner.show();
    this.CouponDetails.venueId = localStorage.getItem('venuesID');
    if(this.CouponDetails._id)
      this.apiService.editCoupon(this.CouponDetails).subscribe((res)=>
        this.spinner.hide();
        if(res.status == true)
         this.router.navigate(['/pages/orders/coupons']);   
          this.showToast('success', '', 'Succesfully updated');
         else 
            this.showToast('danger', '', 'Error');
         
      );
     else 
      this.apiService.saveCoupon(this.CouponDetails).subscribe((res)=>
        this.spinner.hide();
        if(res.status == true)
          this.router.navigate(['/pages/orders/coupons']);   
          this.showToast('success', '', 'Succesfully added');
         else 
            this.showToast('danger', '', 'Error');
         
      );
    
  
  
  cancel()
    this.router.navigate(['/pages/orders/coupons']);   
  

  numberOnly(event): boolean 
    const charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) 
      return false;
    
    if(this.CouponDetails.offerPercentage>99)
      return false;
    
    return true;
  

  dotCount:any;
  checkNumberOnly:any;
  checkString:any;
  cdr:any;
  numberOnly2(event): boolean           
    const charCode = (event.which) ? event.which : event.keyCode;      
    if (charCode == 46) 
        this.dotCount += 1;
        this.checkNumberOnly = (event.target.value);
        var numericCheck = (event.target.value).toString();
        if (numericCheck.includes('.')) 
          this.dotCount += 1;
        
        if (this.dotCount > 1)    
            this.dotCount = 0;
            return false;
        
    
    if (charCode > 31 && (charCode < 45 || charCode > 57 || charCode==47)) 
        return false;
    
    this.checkNumberOnly = (event.target.value);
    if (this.checkNumberOnly != null) 
        var numeric = (event.target.value).toString();
        if (numeric.includes('.')) 
            var checkNumeric = numeric.split('.');
            if (checkNumeric.length > 2) 
                return false;
            
            this.checkString = checkNumeric[1].split('');
            if (this.checkString.length > 1) 
              return false;
            
        
    
    this.dotCount = 0;
    return true;
   

  onKeydown(event) 
    if (event.keyCode === 32 ) 
      return false;
        
  
  
  config: ToasterConfig;

  private showToast(type: NbComponentStatus, body: string, title: string) 
    const config = 
      status: type,
      destroyByClick: true,
      duration: 2000,
      position: NbGlobalPhysicalPosition.TOP_RIGHT,
      preventDuplicates: false,
    ;
    const titleContent = title ? `$title` : '';
    this.toastrService.show(
      body,
      `$titleContent`,
      config);
  



Spect.ts

import  async, ComponentFixture, TestBed  from '@angular/core/testing';

import  EditCouponComponent  from './edit-coupon.component';

describe('EditCouponComponent', () => 
  let component: EditCouponComponent;
  let fixture: ComponentFixture<EditCouponComponent>;

  beforeEach(async(() => 
    TestBed.configureTestingModule(
      declarations: [ EditCouponComponent ]
    )
    .compileComponents();
  ));

  beforeEach(() => 
    fixture = TestBed.createComponent(EditCouponComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  );

  it('should create', () => 
    expect(component).toBeTruthy();
  );
);


谢谢.................................................. ..................................................... ..................................................... ..................................................... ..................................................... ..................................................... ....................

【问题讨论】:

【参考方案1】:

您需要导入在您的规范文件中声明 nb-card-header 元素的组件,并在其中提及 configureTestingModule 作为导入。

// spec.ts
import  async, ComponentFixture, TestBed  from '@angular/core/testing';

import  EditCouponComponent  from './edit-coupon.component';

// I have assumed ng-card-header element is declared within NbComponentStatus. Use appropriate module/component.
import  NbComponentStatus  from '@nebular/theme';

describe('EditCouponComponent', () => 
  let component: EditCouponComponent;
  let fixture: ComponentFixture<EditCouponComponent>;

  beforeEach(async(() => 
    TestBed.configureTestingModule(
      declarations: [ EditCouponComponent ],
      imports: [ NbComponentStatus ],
    )
    .compileComponents();
  ));

// rest of spec file code

要解决错误 Can't bind to 'ngModel' since it isn't a known property of 'input',您需要导入 FormsModule 并以与上述类似的方式提及它。

【讨论】:

当我编辑我的规范并添加这个时,显示这个错误,'NbComponentStatus' only refers to a type, but is being used as a value here.【参考方案2】:

我已经解决了添加“NbCardModule”的问题。

【讨论】:

以上是关于Angular Karma - nb-card-header' 不是已知元素的主要内容,如果未能解决你的问题,请参考以下文章

Angular - Jasmine/karma - 订阅 lambda 表达式未执行

Karma 为具有无效行号的 Angular 项目生成 lcov 报告

错误:在 Angular CLI >6.0 中,Karma 插件现在由“@angular-devkit/build-angular”导出

使用 Karma 测试 Angular 时选择性地模拟服务

使用 karma 和 jamis 进行 Angular 单元测试

Karma 测试 Angular - TypeError:无法读取 null 的属性“recipientAddressId”