我正在尝试对使用第三方控件(来自Clarity)的Angular 4组件进行单元测试 . 我已经使用正确的导入设置了测试模块,但是html中的清晰度元素只是作为元素保留 - 它们没有被解析并按预期扩展为html,即控件似乎没有经历正确的渲染周期 . 这是设置:

import { ClarityModule } from 'clarity-angular';
import { Alert } from '../../shared/components/alert.component';
import { AlertMessage, AlertStatus } from '../../shared/types/alert.message.type';

describe('Alert component tests->', () => {
    let comp: Alert;
    let fixture: ComponentFixture<Alert>;
    let de: DebugElement;
    let el: HTMLElement;
    let deIcon: DebugElement;
    let elIcon: HTMLElement;

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        imports: [ClarityModule],
        declarations: [Alert]
      });
    }));

当我检查夹具debugElement或nativeElement时,它没有被转换?当我尝试选择一个预期的元素时,它不存在 . 是否有一些技巧我想让控件渲染?

组件html模板看起来像这样,并保持这样:

<clr-alert [clrAlertType]="alertType" [clrAlertSizeSmall]="isSmall" [clrAlertAppLevel]="isAppLevel" [clrAlertClosable]="isCloseable">
  <div class="alert-item">
    <span class="alert-text">
      {{message}}
    </span>
  </div>
</clr-alert>

编辑:经过一些拔毛后我发现我需要调用fixture.detectChanges()来获取测试床来渲染组件 . 总之,在测试第三方组件时:

  • 确保已将包含组件的模块导入试验台

  • 如果出现错误,不要只将CUSTOM_ELEMENTS_SCHEMA添加到测试模式中,尝试找出其发生的原因并导入正确的模块(除非您进行浅层测试)

  • 在尝试选择组件呈现的任何元素之前调用fixture.detectChanges()(然后在角度文档站点上的大多数示例中设置属性后再次调用它) .