在测试时如何模拟子组件?我有一个名为product-selected的父组件,其模板如下所示:

<section id="selected-container" class="container-fluid">
    <hr/>
  <product-settings></product-settings>
  <product-editor></product-editor>
  <product-options></product-options>
</section>

组件声明如下所示:

import { Component, Input }               from '@angular/core'; 

import { ProductSettingsComponent } from '../settings/product-settings.component';                                      
import { ProductEditorComponent }   from '../editor/product-editor.component';                                      
import { ProductOptionsComponent }  from '../options/product-options.component';                                        

@Component({
    selector: 'product-selected',
    templateUrl: './product-selected.component.html',
    styleUrls: ['./product-selected.component.scss']
})
export class ProductSelectedComponent {}

这个组件实际上只是其他组件居住的地方,可能不包含任何其他功能.

但当我设置测试时,我得到了以下模板错误,这对所有三个组件都是重复的:

Error: Template parse errors:
    'product-editor' is not a known element:
    1. If 'product-editor' is an Angular component, then verify that it is part of this module.
    2. If 'product-editor' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
        <hr/>
      <product-settings></product-settings>
      [ERROR ->]<product-editor></product-editor>

我试着加载子组件的模拟版本,但不知道怎么做-我看到的示例只是覆盖父组件,甚至没有提到子组件.那么我该怎么做呢?

推荐答案

小心那NO_ERRORS_SCHEMA块.让我们引用同样的文件的另一部分:

没有错误的浅层组件测试模式极大地简化了复杂模板的单元测试.但是,编译器不再提醒您拼写错误或误用组件和指令等错误.

我发现这一缺点与编写测试的目的完全背道而驰.更重要的是,模拟一个基本组件并不是那么困难.

这里还没有提到的一种方法就是在配置时声明它们:

@Component({
  selector: 'product-settings',
  template: '<p>Mock Product Settings Component</p>'
})
class MockProductSettingsComponent {}

@Component({
  selector: 'product-editor',
  template: '<p>Mock Product Editor Component</p>'
})
class MockProductEditorComponent {}

...  // third one

beforeEach(() => {
  TestBed.configureTestingModule({
      declarations: [
        ProductSelectedComponent,
        MockProductSettingsComponent,
        MockProductEditorComponent,
        // ... third one
      ],
      providers: [/* your providers */]
  });
  // ... carry on
});

Angular相关问答推荐

日语字符不受角形约束控制

如何使用解析器处理Angular 路由中存储的查询参数以避免任何额外的导航?

@ngrx/调度时未定义存储操作

如何在Angular功能路由保护中取消订阅RxJs主题

npm install命令在基本Angular 应用程序的天蓝色构建管道中失败

在指令中获取宿主组件的templateRef

Angular 9表单构建器 - 日期验证器问题

大型 Angular 12 应用程序 - 我如何管理 js 文件

没有调用订阅的原因是什么?

角 12 固态继电器 |页眉页脚在加载程序到来之前显示

将 injectiontoken 用于 Angular 中的模块特定设置

Aws 代码部署在 BeforeBlockTraffic 步骤失败,即使在更新策略后也会超时

在 Angular material表上调用 renderRows()

angular4应用程序中输入的最小值和最大值

更改 Select 选项时获取当前值

ngx-toastr,Toast 未在 Angular 7 中显示

将外部 CSS 加载到组件中

错误:angular2 中没有 HttpHandler 的提供者

如何在 Angular CLI 的构建时插入内部版本号或时间戳

如何在Angular 2中将对象从一个组件传递到另一个组件?