0

问题

在测试 Angular 组件时,我经常偶然发现以下错误消息:

'NG0304: 'app-chip' is not a known element:
1. If 'app-chip' is an Angular component, then verify that it is part of this module.
2. If 'app-chip' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.'

原因

这通常是因为我<app-chip>在模板中使用了一个组件(这里:):

<div class="asanas-filter">
  <app-filter-sticky-header [optionIds]="['asanas']"> Asanas </app-filter-sticky-header>

  <div class="chips" *ngIf="asanas">
    <app-chip
      *ngFor="let asana of asanas"
      [label]="asana.label"
      [(model)]="model[asana.id]"
    ></app-chip>
  </div>
  <app-filter-footer [optionIds]="['asanas']" [groupOption]="true"></app-filter-footer>
</div>

并忘记将模拟组件添加到规范文件中:

TestBed.configureTestingModule({
  declarations: [
    AsanasFilterComponent,
    MockComponent(FilterStickyHeaderComponent),
    MockComponent(FilterFooterComponent),
    // MockComponent(AppChipComponent) is missing here
  ],
}).compileComponents();

我正在使用ng-mocks来模拟组件。

所需的解决方案

我认为,必须手动将模板中使用的组件添加到测试配置中不会有利于开发过程:如果我忘记将我正在使用的组件导入到当前模块中(或者在拼写错误的情况下),构建无论如何都会失败。(因为我不想使用CUSTOM_ELEMENTS_SCHEMA

有没有办法自动将我在模板中使用的所有组件作为 Mocks 添加到声明数组中?

还是有理由不这样做(并继续手动添加它们)?

4

1 回答 1

1

你要找的是MockBuilder

在它的帮助下,您只需要一个组件及其模块,其余的将默认自动模拟。

beforeEach(() => MockBuilder(AsanasFilterComponent, AsanasFilterModule));

如果AsanasFilterModuleimports / declares FilterStickyHeaderComponentFilterFooterComponentand AppChipComponent,那么它们将被嘲笑。

这里的目标与避免相同CUSTOM_ELEMENTS_SCHEMA:如果开发人员删除了声明或导入 from AsanasFilterModule,则相关测试将由于缺少 mock in 而失败MockBuilder

于 2022-01-19T07:00:55.763 回答