错误:模板解析错误:没有将“ exportAs”设置为“ matAutocomplete”(“” auto“ [formControl] =” ...“

时间:2019-11-25 11:55:52

标签: javascript angular typescript unit-testing

我正在编写单元测试,以检查是否成功创建了组件。我看到以下错误  错误:模板解析错误:没有将“ exportAs”设置为“ matAutocomplete”(“” auto“ [formControl

这是我的template.html,其中包含自动完成指令

<mat-form-field >
  <input matInput [matAutocomplete]="auto"  [formControl]="customerFilterControl">
  <mat-autocomplete panelWidth ="450px" #auto="matAutocomplete" [displayWith] = "displayFn" style="width:750px;">
     <mat-option  *ngFor="let customer of filteredOptions | async" [value] ="customer.AccountID + '('+ customer.AccountName + ')'" (click)="onCustomerChange(customer)">
      {{customer.AccountID}} ({{customer.AccountName}})
     </mat-option>
  </mat-autocomplete>
</mat-form-field>

这是单元测试spec.file,我已经尝试了以下操作,

import { ActualComponent } from './ActualComponent';
import { NO_ERRORS_SCHEMA,CUSTOM_ELEMENTS_SCHEMA,Directive } from '@angular/core'; 

@Directive({
  selector:'<matAutocomplete>',
})
export class matAutocomplete{}

 beforeEach(()=>{
  TestBed.configureTestingModule({
       imports:[....],
      declarations:[...matAutocomplete],(1)
       ...
     schemas:[NO_ERRORS_SCHEMA,CUSTOM_ELEMENTS_SCHEMA] //this didn't fix (2)
})

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

我希望测试通过(1)定义指令“ matAutocomplete”并在规范文件中声明(2)在测试平台配置中对模式进行除垢,但测试仍未通过!有人对我有建议吗?

1 个答案:

答案 0 :(得分:1)

选择器<matAutocomplete>将不起作用。尝试使用[matAutoComplete]并将@Input() matAutocomplete添加到类中。下一步是将exportAs添加到指令装饰器:

@Directive({
  selector:'[matAutocomplete]',
  exportAs: 'matAutocomplete'
})
export class matAutocomplete {
   @Input() matAutocomplete: any;
}

更新 也许最好用导入的角度材料模块对此进行测试。否则,测试不会真正测试任何相关内容。

您可以尝试以下方法吗?

1)

import {ReactiveFormsModule} from '@angular/forms';
import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatInputModule} from '@angular/material/input';
import {MatSelectModule} from '@angular/material/select';
import {MatFormFieldModule} from '@angular/material/form-field';


...
// inside beforeEach:
TestBed.configureTestingModule({
  imports:[ReactiveFormsModule, 
           MatAutocompleteModule, MatInputModule, 
           MatSelectModule, MatFormFieldModule],
  declarations:[AppComponent],  // add your component instead of AppComponent

  // schemas:[NO_ERRORS_SCHEMA,CUSTOM_ELEMENTS_SCHEMA] 
});

2)删除自定义matAutocomplete指令。