在测试时如何模拟子组件?我有一个名为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。
import { NO_ERRORS_SCHEMA } from '@angular/core'; TestBed.configureTestingModule({ declarations: declarations,providers: providers schemas: [ NO_ERRORS_SCHEMA ] })
基于文档:
Add NO_ERRORS_SCHEMA to the testing module’s schemas Metadata to tell the compiler to ignore unrecognized elements and attributes. You no longer have to declare irrelevant components and directives.
更多相关信息:https://angular.io/docs/ts/latest/guide/testing.html#!#shallow-component-test