单元测试中出现前缀图标错误的角按钮组件

问题描述 投票:0回答:0

非常感谢您对此主题的帮助。

我有一个自定义按钮组件,它带有一个名为 prefix 的 @Input 属性,它加载了一个与按钮可能具有的图标相关的 ng-template。

(button.component.ts)
@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.scss'],
})
export class ButtonComponent {
  @Input() prefix?: TemplateRef<void>;
  /* ... other attributes, constructor and more */
}
(button.component.html)
<button
  [type]="isSubmit ? 'submit' : 'button'"
  nz-button
  <!-- other attributes -->
  (click)="clickHandler($event)"
>
  <ng-container *ngIf="prefix">
    <span nz-tooltip class="prefix" [nzTooltipTitle]="tooltip || ''">
      <ng-container [ngTemplateOutlet]="prefix"></ng-container>
    </span>
  </ng-container>
  {{ text }}
</button>
(sample.component.html)
<div class="sample-content">
  <app-button
    [prefix]="showHideIconTpl!"
    tooltip="Show/Hide columns"
  ></app-button>
</div>
<ng-template #showHideIconTpl>
  <em class="fas fa-tasks"></em>
</ng-template>

在执行

ng serve
时将前缀作为 ng-template 在 html 中传递有效,但是,当使用
ng test
运行单元测试时,会发生此错误:

describe('SampleComponent', () => {
  beforeEach(() => {
    fixture = TestBed.createComponent(SampleComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  fit('Should create', () => {
    expect(component).toBeTruthy();
  });
});
1) Should create
     SampleComponent
     TypeError: Cannot set property prefix of [object Element] which has only a getter
    at EmulatedEncapsulationDomRenderer2.setProperty (node_modules/@angular/platform-browser/__ivy_ngcc__/fesm2015/platform-browser.js:744:1)
    at elementPropertyInternal (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10026:1)
    at ɵɵproperty (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:14787:1)
    at SampleComponent_Template (ng:///SampleComponent.js:92:9)

问题部分: 如何保证html中带有[prefix]属性的按钮不影响单元测试? Web 组件也显示成功,只是前缀图标的情况影响了配置中缺少的单元测试的某些内容?

最好的问候,

html angular typescript karma-jasmine
© www.soinside.com 2019 - 2024. All rights reserved.