LoginSignup
6
8

More than 5 years have passed since last update.

Angular コンポーネントのテスト(angular/cli で生成されるコンポーネントのテストコード)

Last updated at Posted at 2018-03-24

目次:Angular コンポーネントのテスト


angular/cli でコンポーネントを作成すると一緒にテストコードも生成されます。雛形とも言えるこのコードには、基本的なコンポーネントのテストが書かれています。まずはコンポーネントを作成し、テストコードを見て見ましょう。

$ ng new project1
$ cd project1
$ ng generate component sample1
// sample1.component.spec.ts

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

import { Sample1Component } from './sample1.component';

describe('Sample1Component', () => {
  let component: sample1Component;
  let fixture: ComponentFixture<Sample1Component>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ Sample1Component ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Sample1Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

雛形のテストコードを理解する

一つ目のbeforeEach

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [ Sample1Component ]
  })
  .compileComponents();
}));

TestBed

TestBed はテスト用の環境に関するメソッドを提供します。
TestBed.configureTestingModule() でテスト用のモジュール情報を設定し compileComponents() でそのモジュールに含まれるコンポーネントをコンパイルします。

コンパイル対象のコンポーネントは declarations で定義します。
コンポーネントがモジュールやサービスに依存している場合や、別のコンポーネントやディレクティブを所有している場合はそれらもコンパイル対象となります。

async

よく見ると処理全体は async という関数で囲われていますね。
これはコンポーネントのコンパイルが非同期で行われるためです。

async は非同期処理の終了を待って次の処理に移るための関数です。
処理全体を囲うことで、beforeEach の次のプロセスに移る時にコンパイルが完了している事を保証できます。

二つ目のbeforeEach

beforeEach(() => {
  fixture = TestBed.createComponent(Sample1Component);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

TestBed.createComponent() は、コンポーネントを作成しそのコンポーネントにアクセスするための ComponentFixture オブジェクトを返却します。

fixture.componentInstance はコンポーネントに紐付いたクラスを参照するためのプロパティです。具体的には Sample1Component クラスのインスタンスを参照します。

component.Fixture.detectChanges() はクラスが持つプロパティをテンプレートに反映します。

it('should create')

it('should create', () => {
  expect(component).toBeTruthy();
});

おなじみの Jasmine のテストスイートですね。
コンポーネントの作成が正常に完了すると変数 component はコンポーネントに紐付いたクラスを参照しているので、値が空でない事を検証しています。

Testing Utility APIs

TestBed や async など、テストに関する機能を提供する一連のオブジェクトや関数群を Testing Utility APIs と呼びます。
このユーティリティを使用する事で、テスト用の環境を生成し、アプリケーションをブラウザで実行させるのと同じように、テスト環境で動作をシミュレートできます。

コンパイルされたコンポーネントには ComponentFixture を通してアクセスする事ができ、クラスのプロパティを検証したり、HTML要素の値を検証したり、といったテストが可能になります。

公式ドキュメント Testing Utility APIs
https://angular.io/guide/testing#testing-utility-apis


次の記事:sample1 / フォームに含まれない単体のHTML要素のテスト

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8