Angular 2 コンポーネントに別のコンポーネントが含まれているかどうかを単体テストする方法 質問する

Angular 2 コンポーネントに別のコンポーネントが含まれているかどうかを単体テストする方法 質問する

私はAngular 2の初心者です。

テンプレート内に他のコンポーネントがいくつか含まれているコンポーネントがあります。

親コンポーネントが他のコンポーネントで構成されているかどうかを確認するための単体テストをどのように記述すればよいですか。

サンプルについて言及したり、リソースを教えていただければ、非常に助かります。

MyComponent.ts:

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

}

その他のコンポーネント.ts:

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

}

ベストアンサー1

コンパイル時にコンポーネントに他のコンポーネントが含まれているかどうかをテストするには:

  • テストするコンポーネントを挿入する
  • 子コンポーネントを注入する
  • 親コンポーネントを作成する
  • 変更を検出する
  • querySelectorまたはを使用しquerySelectorAllて子コンポーネントを検索します

通常は、要素が存在することのみを確認し、その後、個々の子コンポーネントの仕様でさらにテストを実行します。

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);
  }));
});

nullをチェックすることでquerySelectorコンポーネントが存在するかどうかが判断されます。クエリセレクター MDN:

一致するものが見つからない場合は null を返します。それ以外の場合は、最初に一致する要素を返します。


同じ子コンポーネントのインスタンスが複数あることを確認したい場合は、querySelectorAll次のプロパティを使用して確認できますlength

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

おすすめ記事