簡體   English   中英

如果角度2組件包含另一個組件,如何進行單元測試

[英]How to unit test if an angular 2 component contains another component

我對棱角2很新。

我有一個組件,其模板中還有一些其他組件。

如何編寫單元測試以檢查我的父組件是否包含其他組件。

提及樣本或指導我使用資源非常有幫助。

MyComponent.ts:

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

}

OtherComponent.ts:

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

}

要測試組件在編譯時是否包含其他組件:

  • 注入您正在測試的組件
  • 注入子組件
  • 創建父組件
  • 檢測更改
  • 使用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);
  }));
});

使用querySelector檢查null將確定您的組件是否存在。 querySelector MDN

如果未找到匹配項,則返回null; 否則,它返回第一個匹配元素。


如果您要檢查是否存在同一子組件的多個實例,則可以使用querySelectorAll並檢查length屬性:

expect(compiled.querySelectorAll('app-other').length).toBeGreaterThan(4);

在大多數情況下,您只是在測試外部組件。 如果您只想讓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';

然后在你的describe塊中你將有一個beforeEach

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

然后您的組件現在應該正確編譯而不會出錯。 如果要查看整個設置,只需在angular-cli中生成一個新項目,然后查看它生成的spec文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM