如果角度2组件包含另一个组件,如何进行单元测试

Cha*_*n15 17 karma-jasmine angular2-testing angular

我对棱角2很新.

我有一个组件,其模板中还有一些其他组件.

如何编写单元测试以检查我的父组件是否包含其他组件.

提及样本或指导我使用资源非常有帮助.

MyComponent.ts:

import { Component } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: `<div>
<other-component></other-component>
</div>`
})
export class MyComponent{

}
Run Code Online (Sandbox Code Playgroud)

OtherComponent.ts:

import { Component } from '@angular/core';
@Component({
selector: 'other-component',
templateUrl: `<div>
<h1>Other Component</h1>
</div>`
})
export class OtherComponent{

}
Run Code Online (Sandbox Code Playgroud)

sil*_*age 25

要测试组件在编译时是否包含其他组件:

  • 注入您正在测试的组件
  • 注入子组件
  • 创建父组件
  • 检测更改
  • 使用querySelectorquerySelectorAll查找子组件

我通常只检查元素是否存在,然后在规范中对单个子组件进行进一步测试.

import { TestBed, async } from '@angular/core/testing';

import { AppComponent } from './app.component';
import { OtherComponent } from './other/other.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        OtherComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it('should have the other component', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('app-other')).not.toBe(null);
  }));
});
Run Code Online (Sandbox Code Playgroud)

检查null querySelector将确定您的组件是否存在.从querySelector MDN:

如果未找到匹配项,则返回null; 否则,它返回第一个匹配元素.


如果您想检查是否存在同一子组件的多个实例,则可以使用querySelectorAll并检查该length属性:

expect(compiled.querySelectorAll('app-other').length).toBeGreaterThan(4);
Run Code Online (Sandbox Code Playgroud)


Fel*_*sai 12

在大多数情况下,您只是在测试外部组件.如果您只想让angular忽略内部组件,最简单的方法是将NO_ERRORS_SCHEMA添加到您的规范中.

从'@ angular/core'导入{NO_ERRORS_SCHEMA}

然后在TestBed.configureTestingModule中添加以下行:

架构:[NO_ERRORS_SCHEMA]

然后,测试将忽略您未在组件HTML中导入内部组件的事实.

如果要使用外部组件测试内部组件,如果您正在使用angular-cli,您将看到它们自动为您生成的component.spec文件包含一个declarations属于TestBed配置对象的数组.因此,您所要做的就是导入文件并将组件添加到声明中.

所以你的例子如上:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { MyComponent } from './my-component.component';
import { OtherComponent } from './other-component.component';
Run Code Online (Sandbox Code Playgroud)

然后在你的describe街区你将有一个beforeEach

beforeEach(async(() =>{
  TestBed.configureTestingModule({
    declarations: [ MyComponent,
                    OtherComponent ]
  })
  .compileComponent();
})
Run Code Online (Sandbox Code Playgroud)

然后您的组件现在应该正确编译而不会出错.如果您想查看整个设置,只需在angular-cli中生成一个新项目,然后查看它生成的规范文档.

  • 这并没有真正回答他们的问题.他们希望确保模板中存在的组件不测试外部组件的内部组件或独立测试组件. (4认同)